SQL保持发生次数

时间:2013-04-04 16:57:26

标签: sql sql-server count sql-server-2012

我在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中实现它。

问候。

3 个答案:

答案 0 :(得分:4)

最简单(也可能是最有效)的方法是使用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是唯一的:

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,其中使用on on -disk spool:

SELECT [Date], Code, [Count] = COUNT(*) OVER (PARTITION BY Code ORDER BY [Date]
  ROWS UNBOUNDED PRECEDING)
 FROM dbo.YourTable
 ORDER BY [Date];

您可能想在桌面上尝试这些选项,看看性能如何。

答案 1 :(得分:0)

看起来你想要一个代码值的运行计数。如果是这样,那么您可以使用以下查询来获取运行计数:

SELECT date,
  code, 
  (SELECT count(code)
   FROM yourtable b 
   WHERE b.date <= a.date
     and a.code = b.code) AS TotalCount
FROM yourtable a

请参阅SQL Fiddle with Demo

或者您可以使用:

SELECT a.date,
  a.code, 
  count(a.code) AS TotalCount
FROM yourtable a
cross join yourtable b
WHERE b.date <= a.date
  and a.code = b.code
group by a.date, a.code
order by a.date;

请参阅SQL Fiddle with Demo

请注意,这可以在较小的表上正常工作,但在较大的表上会出现问题。 (谢谢@AaronBertrand)

答案 2 :(得分:0)

如果我理解正确,你想添加额外的列,告诉你代码发生了多少次。

select *, 
COUNT(1) over (partition by Code) 
from Table