输出表中id的出现次数

时间:2017-07-11 08:01:44

标签: sql sql-server

PK     Date      ID
=== =========== ===    
1   07/04/2017   22
2   07/05/2017   22  
3   07/07/2017   03    
4   07/08/2017   04     
5   07/09/2017   22    
6   07/09/2017   22    
7   07/10/2017   05
8   07/11/2017   03    
9   07/11/2017   03    
10  07/11/2017   03

我想计算给定周/月内发生的ID数量,类似这样。

ID  Count
22    3   --> count as 1 only in the same date occurred twice one 07/09/2017
03    2   --> same as above, increment only one regardless how many times it occurred in a same date
04    1
05    1

我正在尝试在perl文件中实现它,在csv文件中输出/打印它,我不知道我将执行什么查询。

3 个答案:

答案 0 :(得分:1)

似乎是一个简单的计数独特的案例和分组:

SELECT Id, COUNT(DISTINCT [Date]) As [Count]
FROM TableName
WHERE [Date] >= @StartDate
AND [Date] <= @EndDate
GROUP BY Id
ORDER BY [Count] DESC

答案 1 :(得分:1)

您可以COUNT使用DISTINCT例如:

SELECT ID, COUNT(DISTINCT Date) 
FROM table
GROUP BY ID;

答案 2 :(得分:0)

您可以阅读更多信息如何从get month from a date中的某个日期获得月份(它也适用于一年)。

您的查询将是:

select DATEPART(mm,Date) AS month, COUNT(ID) AS count from table group by month

希望能帮到你。