我具有以下表格结构,我需要根据购买的总数量以递减的方式为每个客户分配一个数字:
customerid order_date item quantity price
10330 2016-06-30 Skateboard 1 28.00
10101 2016-06-30 Raft 1 58.00
10298 2016-07-01 Skateboard 1 33.00
10101 2016-07-01 Snow Shoes 4 125.00
10299 2016-07-06 Parachute 1 1250.00
10339 2016-07-27 Umbrella 1 4.500
10449 2016-08-13 Bicycle 1 180.790
10439 2016-08-14 Ski Poles 2 25.500
到目前为止,我一直在尝试以下查询,但看起来仍然不正确:
SELECT *, ROW_NUMBER() OVER(PARTITION BY customerid ORDER BY sum(quantity) DESC) FROM IMP_MyTablee
GROUP BY customerid, order_date, item, quantity, price
有人可以给我小费吗?谢谢
所需的输出
无论有多少条记录,购买的总数量以及排名如何,我都需要查看一次CustomerID
:
customerid order_date item quantity price rank
10330 2016-06-30 Skateboard 5 28.00 1
10101 2016-06-30 Raft 3 58.00 3
10298 2016-07-01 Skateboard 4 33.00 2
答案 0 :(得分:1)
尝试一下。先组然后排名
with A as (
select * from
( values
(10330, '2016-06-30', 'Skateboard', 1, 28.00),
(10101, '2016-06-30', 'Raft' , 1, 58.00),
(10298, '2016-07-01', 'Skateboard', 1, 33.00),
(10101, '2016-07-01', 'Snow Shoes', 4, 125.00),
(10299, '2016-07-06', 'Parachute' , 1, 1250.00),
(10339, '2016-07-27', 'Umbrella' , 1, 4.500),
(10449, '2016-08-13', 'Bicycle' , 1, 180.790),
(10439, '2016-08-14', 'Ski Poles' , 2, 25.500)
) as T(customerid, order_date, item, quantity, price)
)
, B as (
select
customerid,
item,
sum(quantity) as total,
price
from
A
group by
customerid, item, price
)
select top(3) *, ROW_NUMBER() over (order by total desc) from B order by total desc
答案 1 :(得分:1)
您的规格要求如下查询:
SELECT customerid,
SUM(Quantity) As Qty
ROW_NUMBER() OVER (GROUP BY customerid ORDER BY Sum(Quantity) desc) As Rank
FROM IMP_MyTablee
GROUP BY customerid
如果还需要详细信息,则需要指定所需的详细信息-SUM(价格*数量)或MIN(订购日期),或其他。...