简体   繁体   中英

TSQL Row_Number

This question has been covered similarly before BUT I'm struggling.

I need to find top N sales based on customer buying patterns..

ideally this needs to be top N by customer by Month Period by Year but for now i'm just looking at top N over the whole DB.

My query looks like:

-- QUERY TO SHOW TOP 2 CUSTOMER INVOICES BY CUSTOMER BY MONTH

SELECT
    bill_to_code,
    INVOICE_NUMBER,
    SUM( INVOICE_AMOUNT_CORP ) AS 'SALES',
    ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC ) AS 'Row'
FROM
    FACT_OM_INVOICE
    JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
--WHERE
--    'ROW' < 2
GROUP BY
    invoice_number,
    Dim_customer_bill_to.bill_to_code

I can't understand the solutions given to restrict Row to =< N.

Please help.

Try this.

-- QUERY TO SHOW TOP 2 CUSTOMER INVOICES BY CUSTOMER BY MONTH
;WITH Top2Customers
AS
(
SELECT
    bill_to_code,
    INVOICE_NUMBER,
    SUM( INVOICE_AMOUNT_CORP ) AS 'SALES',
    ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC ) 
    AS 'RowNumber'
FROM
    FACT_OM_INVOICE
    JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
GROUP BY
    invoice_number,
    Dim_customer_bill_to.bill_to_code
)
SELECT * FROM Top2Customers WHERE RowNumber < 3

You have to wrap your select into another to use the value produced by row_number()

select * from (
SELECT
    bill_to_code,
    INVOICE_NUMBER,
    SUM( INVOICE_AMOUNT_CORP ) AS SALES,
    ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC ) AS RowNo
FROM
    FACT_OM_INVOICE
    JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
--WHERE
--    'ROW' < 2
GROUP BY
    invoice_number,
    Dim_customer_bill_to.bill_to_code
) base where RowNo < 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM