SQL Query获取top [n]记录,但有一个转折点

时间:2015-07-14 17:47:43

标签: sql sql-server sql-server-2012

我有一个包含数十万条记录的库存表。让我们说这是最初的几条记录:

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

我如何得到这样的结果:

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

这可以通过PIVOT功能完成吗?或者可能还有其他SQL函数(MAX,TOP n等等?)

1 个答案:

答案 0 :(得分:2)

一种方法是使用窗口函数row_number()并按item_cat,item分区,然后使用条件聚合。

这样的事情应该有效:

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

这应该适用于2005年以来所有版本的SQL Server(如果内存对我有用)。