SQL分组和密集排名概念

时间:2017-07-09 07:23:28

标签: sql

我的数据集如下:

 cust   city    hotel_id amount
 -------------------------------
   A    1        252    3160
   B    1        256    1893
   C    2        105    2188
   D    2        105    3054
   E    3        370    6107
   F    2        110    3160
   G    2        150    1893
   H    3        310    2188
   I    1        252    3160
   J    1        250    4000
   K    3        370    5000 
   L    3        311    1095

查询按每个城市的收入(金额总和)显示前3家酒店? 由于同一酒店可以由同一城市的其他客户预订,因此我们需要汇总金额以查找总金额。

预期产出:

city    hotel_id    amount
---------------------------
  1       252        6320
  1       250        4000
  1       256        1893

  2       105        5242
  2       110        3160
  2       150        1893

  3       370       11107
  3       310        2188
  3       311        1095

2 个答案:

答案 0 :(得分:1)

SELECT
    t.city, t.hotel_id, t.amount
FROM
(
    SELECT city, hotel_id, SUM(amount) AS amount,
        ROW_NUMBER() OVER (PARTITION BY city ORDER BY SUM(amount) DESC) AS rn
    FROM yourTable
    GROUP BY city, hotel_id
) t
WHERE t.rn <= 3
ORDER BY t.city, t.amount DESC;

在这里演示:

Rextester

答案 1 :(得分:0)

要获取每个hotel_id的总和,您需要先按该列分组,然后按城市分组以获取语法。这里的#tmp表应该包含您需要的所有数据,因此您只需从那里为每个城市选择前3个条目。

SELECT city, hotel_id, SUM(amount) AS 'total' INTO #tmp
FROM [table]
GROUP BY hotel_id, city

(SELECT TOP 3 *
FROM #tmp
WHERE city = 1)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 2)
UNION
(SELECT TOP 3 *
FROM #tmp
WHERE city = 3)