2015-09-26 58 views
0
排了一天结果

我的表是这样的:SQL查询来获取从列两个条件,并在

Date  | ID 
-----------+----------- 
2015-07-01 | 10 
2015-07-01 | 10 
2015-06-01 | 10 
2015-07-01 | 10 
2015-06-01 | 10 
2015-07-01 | 10 
2015-03-01 | 10 
2015-02-01 | 10 
2015-07-01 | 10 
2015-07-01 | 10 
2015-03-12 | 10 
2015-02-09 | 10 
2015-07-05 | 10 
2015-07-03 | 10 

我需要每月在列行一天,我需要发送的参数中的第一和上个月得到

我需要看起来像这样的结果,它需要计算当月在当月发生多少事件。

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 
02 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
03 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
06 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
07 6 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  
+0

我认为这是可能的 “支点” –

回答

1

这是一个数据透视查询。 SQL Server以pivot语句的形式具有特殊的语法。我一般喜欢使用有条件聚集:

select month([date]) as mon, 
     sum(case when day([date]) = 1 then 1 else 0 end) as day_01, 
     sum(case when day([date]) = 2 then 1 else 0 end) as day_02, 
     . . . 
     sum(case when day([date]) = 31 then 1 else 0 end) as day_31 
from table t 
group by month([date]) 
order by mon; 

如果不使用SQL Server中,大多数数据库非常类似的语法著作,虽然day()month()的功能可能会有所不同。

此外,如果您的数据跨多个日历年,您可能还需要在聚合中包含年份。

1

这是你将如何使用PIVOT做到这一点:

select p.* 
from (
    select day([Date]) as [Day], 
     month([Date]) as [Month] 
    from [Table] 
) t 
pivot (
    count([Day]) 
    for [Day] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10], 
       [11],[12],[13],[14],[15],[16],[17],[18],[19],[20], 
       [21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]) 
) p 
where p.[Month] between 1 and 12 -- adjust first and last month here. 
order by p.[Month] 

SQLFiddle Demo