SQL Server:查询DENSE_RANK()按2列分组?

时间:2015-09-17 06:55:13

标签: sql-server sql-server-2008

需要帮助构建SQL,通过订单表,它包含Date,SalesID,ItemID和其他misc。列。 表格如下:

Date                   SalesID      ItemID
13-9-15 6:15:00         56            6
13-9-15 6:00:00         56            6
13-9-15 6:26:00         56            4
13-9-15 6:38:00         34            4
13-9-15 7:05:00         34            2
13-9-15 6:42:00         12            2
13-9-15 7:20:00         12            5
13-9-15 7:34:00         78            5
13-9-15 7:41:00         78            6

作为附加列,我想要的是,每当新SalesID按日期开始排序时,每个计数器都会递增。计数器列将计数直到最大值为3.我正在使用DENSE_RANK()对于增量列。

最后我需要的是:

Date                  SalesID       ItemID     Counter
13-9-15 6:00:00          56           6          1
13-9-15 6:15:00          56           6          1
13-9-15 6:26:00          56           4          1
13-9-15 6:38:00          34           4          2
13-9-15 6:42:00          34           2          2
13-9-15 7:05:00          12           2          3
13-9-15 7:20:00          12           5          3
13-9-15 7:34:00          78           5          1
13-9-15 7:41:00          78           6          1

1 个答案:

答案 0 :(得分:0)

此解决方案适用于sqlserver 2012+。我必须更正示例中的无效数据才能获得正确的输出

DECLARE @t table(Date datetime, SalesID int, ItemID int)
INSERT @t values
('2015-09-13 6:15:00',56,6),
('2015-09-13 6:00:00',56,6),
('2015-09-13 6:26:00',56,4),
('2015-09-13 6:38:00',34,4),
('2015-09-13 6:42:00',34,2),
('2015-09-13 7:05:00',12,2),
('2015-09-13 7:10:00',12,5),
('2015-09-13 7:34:00',78,5),
('2015-09-13 7:41:00',78,6)

;WITH CTE as
(
  SELECT 
    [Date], [SalesID], [ItemID],
    CASE WHEN lag(SalesID) over (order by Date) = SalesID 
         THEN 0 ELSE 1 END x
  FROM @t
)
SELECT 
  [Date], [SalesID], [ItemID],
  (sum(x) over (ORDER BY Date) - 1) % 3 + 1  [Counter]
FROM CTE

结果:

Date              SalesID  ItemID   Counter
2015-09-13 06:00  56       6        1
2015-09-13 06:15  56       6        1
2015-09-13 06:26  56       4        1
2015-09-13 06:38  34       4        2
2015-09-13 06:42  34       2        2
2015-09-13 07:05  12       2        3
2015-09-13 07:10  12       5        3
2015-09-13 07:34  78       5        1
2015-09-13 07:41  78       6        1

这适用于sqlserver 2008:

;WITH CTE as
(
SELECT
  [Date], 
  SalesID,
  ItemID,
  row_number() over (order by Date)-
    row_number() over (partition by SalesID order by Date) x
 FROM @t
)
SELECT 
  [Date], 
  SalesID,
  ItemID,
  (dense_rank() over (order by x) - 1) % 3 + 1 [Counter]
FROM CTE