对记录进行分组时如何使用ROW_NUMBER?

时间:2018-09-12 16:04:55

标签: sql sql-server sql-server-2016

我有以下内容:

DECLARE @items TABLE
(
    ItemId int NOT NULL,
    [Description] varchar(255) NOT NULL,
    Amount money NOT NULL
);

INSERT INTO @items SELECT 1, 'A', 10;
INSERT INTO @items SELECT 2, 'A', 10;
INSERT INTO @items SELECT 3, 'B', 11;
INSERT INTO @items SELECT 4, 'B', 11;
INSERT INTO @items SELECT 5, 'B', 11;
INSERT INTO @items SELECT 6, 'C', 12;
INSERT INTO @items SELECT 7, 'C', 12;
INSERT INTO @items SELECT 8, 'A', 10;
INSERT INTO @items SELECT 9, 'A', 10;

SELECT 
    ROW_NUMBER() OVER(PARTITION BY b.ItemId ORDER BY b.[Description]),
    [Description],  
    COUNT(ItemId) OVER(PARTITION BY b.ItemId),
    SUM(Amount) OVER(PARTITION BY b.ItemId)
FROM @items b

结果应为:

1, A, 4, 40
2, B, 3, 33
3, C, 2, 24

但是没有将项目分组。

那么我该如何使用ROW_NUMBER对记录进行分组?

2 个答案:

答案 0 :(得分:2)

这是您想要的吗?

SELECT ROW_NUMBER() OVER (ORDER BY i.Description),
       i.Description,  
       COUNT(*),
       SUM(i.Amount) 
FROM @items i
GROUP BY Description
ORDER BY Description;

这里是postgres wiki

答案 1 :(得分:0)

如果您不想单独使用GROUP BY,则可以使用两个row_number()进行子查询,如下所示:

select ROW_NUMBER() over(order by t.[Description]), t.Description, t.cnt, t.summ
from (
SELECT 
    ROW_NUMBER() OVER(PARTITION BY b.[Description] ORDER BY b.[Description] )  rn,
    [Description],  
    COUNT(ItemId) OVER(PARTITION BY b.[Description]) cnt,
    SUM(Amount) OVER(PARTITION BY b.[Description]) summ
FROM @items b
) t where rn = 1

无论如何,您不应该按ItemId对数据进行分组-这是实现目标的错误方法