SQL Keeping count of occurrences

早过忘川 提交于 2019-12-24 01:41:23

问题


I've the following problem I need to solve in SQL.

Let's say that I have a table with 2 columns:

    Date | Code
    --------
    0    | 25
    1    | 22
    2    | 23
    3    | 25
    4    | 23
    5    | 21

And I need to keep a count of them, as the Date is relevant for me. So, let's say that I would need to produce something like this:

    Date | Code | Count
    --------------------
    0    | 25   |   1
    1    | 22   |   1
    2    | 23   |   1
    3    | 25   |   2
    4    | 23   |   2
    5    | 21   |   1

Thanks in advance,

PS: I'm implementing it in MSSQL 2012.

Regards.


回答1:


The simplest (and probably most efficient) approach is to use ROW_NUMBER():

SELECT [Date], Code, [Count] = ROW_NUMBER() OVER (PARTITION BY Code ORDER BY [Date])
 FROM dbo.YourTableName
 ORDER BY [Date];

For fun, you can also solve it this way in SQL Server 2012. If Date is unique:

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

Or more simply:

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

If Date is not unique, and if you don't want ties (same count for identical combinations of date+code), you need to use the more expensive ROWS, which uses 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];

You may want to try each of these options on your table to see what the performance is like.




回答2:


If i understood you correctly you want to add extra column that will tell you how many times that Code occurred.

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



回答3:


It looks like you want a running count of the code values. If so, then you can use the following query to get a running count:

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

See SQL Fiddle with Demo

Or you can use:

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;

See SQL Fiddle with Demo

Note, this will work fine on smaller tables but on larger tables there will be issues. (Thanks @AaronBertrand)



来源:https://stackoverflow.com/questions/15817239/sql-keeping-count-of-occurrences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!