我有以下问题需要在SQL中解决。
假设我有一个包含2列的表格:
Date | Code -------- 0 | 25 1 | 22 2 | 23 3 | 25 4 | 23 5 | 21
我需要保留它们的数量,因为日期与我有关。因此,假设我需要产生以下内容:
Date | Code | Count -------------------- 0 | 25 | 1 1 | 22 | 1 2 | 23 | 1 3 | 25 | 2 4 | 23 | 2 5 | 21 | 1
提前致谢,
PS:我正在MSSQL 2012中实现它。
问候。
最简单(可能是最有效)的方法是使用ROW_NUMBER():
ROW_NUMBER()
SELECT [Date], Code, [Count] = ROW_NUMBER() OVER (PARTITION BY Code ORDER BY [Date]) FROM dbo.YourTableName ORDER BY [Date];
为了娱乐,您也可以在SQL Server 2012中用这种方式解决它。如果Date唯一,则:
Date
SELECT [Date], Code, [Count] = COUNT(*) OVER (PARTITION BY Code ORDER BY [Date] RANGE UNBOUNDED PRECEDING) FROM dbo.YourTable ORDER BY [Date];
或更简单地说:
SELECT [Date], Code, [Count] = COUNT(*) OVER (PARTITION BY Code ORDER BY [Date]) FROM dbo.YourTable ORDER BY [Date];
如果Date不是唯一的,并且如果您不想要领带(相同的日期和代码组合的计数相同),则需要使用更昂贵的ROWS,它在磁盘假脱机上使用:
ROWS
SELECT [Date], Code, [Count] = COUNT(*) OVER (PARTITION BY Code ORDER BY [Date] ROWS UNBOUNDED PRECEDING) FROM dbo.YourTable ORDER BY [Date];
您可能想尝试表上的每个选项,以查看性能如何。