简体   繁体   中英

SQL Query to get the top [n] records, with a twist

I have an inventory table with hundreds of thousands of records. Let's say these are the first few records:

Item_Cat    Item    City     Qty
---------------------------------
Furniture   Table   Boston   150
Furniture   Table   Phoenix  175
Furniture   Table   Tampa    300
Furniture   Chair   Dallas   150
Furniture   Chair   Boston   150
Furniture   Chair   LA       220
Furniture   Chair   Boise    50
Furniture   Sofa    Chicago  110
Hardware    Hammer  New York 750
Hardware    Hammer  LA       50

How can I get the results like this:

Item_Cat    Item    Max_City1 Max_Qty1 Max_City2 Max_Qty2
----------------------------------------------------------
Furniture   Table   Tampa     300      Phoenix   175
Furniture   Chair   LA        220      Boston    150
Furniture   Sofa    Chicago   110      NULL      NULL
Hardware    Hammer  New York  750      LA        50

Can this be done with the PIVOT function? Or maybe with other SQL functions (MAX, TOP n, etc. maybe?)

One way is to use the window function row_number() and partition by item_cat, item and then use conditional aggregation.

Something like this should work:

WITH cte AS (
    SELECT 
       Item_Cat, Item, City, Qty, 
       rn = ROW_NUMBER() OVER (PARTITION BY Item_Cat, Item ORDER BY Qty DESC) 
    FROM t -- your table
)

SELECT 
    Item_Cat
    , Item
    , Max_City1 = MAX(CASE WHEN rn = 1 THEN City END) 
    , Max_Qty1  = MAX(CASE WHEN rn = 1 THEN Qty  END)
    , Max_City2 = MAX(CASE WHEN rn = 2 THEN City END)
    , Max_Qty2  = MAX(CASE WHEN rn = 2 THEN Qty  END)
FROM cte 
GROUP BY Item_Cat, Item
ORDER BY Item_Cat, Max_qty1 DESC

Sample SQL Fiddle

This should work in all versions of SQL Server from 2005 (if memory serves me right).

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