什么是SQL查询以返回日期范围内每个属性的行数?

时间:2015-12-07 22:22:41

标签: sql-server ms-access

我在Access数据库中有一个名为PDA_COLLECTOR_SCCS的表,我想查询每DistrictPickupDate的行数。 District是一个字符串,表示客户端的区域,PickupDate是服务订单完成的时间。 PickupDate格式为mm/d/yyyy。从10/1/2007开始到today

例如,每个地区的每个月都应该有一个整数输出,即DistrictName, EVDate Range 10/1/2007 - 10/31/2007RowCount, 564

编辑: 它是SQL Server 2008

SELECT District, Convert(date, PickupDate) As PickUpMonth, Count(*) As Row_Count FROM dbo.V_PickupAllColumns GROUP BY District, Convert(date, PickupDate)

enter image description here

此查询返回每个区每天的行数,如何更改此值以返回每月每月的行数,即10/1 / 2007-10 / 31/2007

1 个答案:

答案 0 :(得分:0)

对任何Count(),Sum(),Avg(),Max()和Min()函数使用聚合查询:

按地区汇总

SELECT District, Count(*) As RowCount
FROM PDA_COLLECTOR_SCCS
GROUP BY District

按地区,月份,年份汇总

如果您希望按月添加,请按列添加为另一个组。以下转换PickUp表示月份和年份。

SELECT District, CONVERT(VARCHAR(2), 
                         CAST(DATEPART(mm, PickUpDate) AS Varchar(2))) + '-' + 
                 CONVERT(VARCHAR(4),  
                         CAST(DATEPART(yyyy, PickUpDate) As Varchar(4))) As PickUpMonth, 
       Count(*) As [RowCount]
FROM PDA_COLLECTOR_SCCS
GROUP BY District, MONTH(PickUpDate), YEAR(PickUpDate)

与日期范围汇总

现在,如果您需要日期范围列,可以使用派生表子查询:

SELECT District, CONVERT(nvarchar(max), 
                         CAST(CAST(GroupYear AS varchar(4)) + '-' + 
                              CAST(GroupMonth AS varchar(2)) + '-' + 
                              CAST(1 AS varchar(1)) As DATETIME), 101) + ' - ' +
                 CONVERT(nvarchar(max), DateAdd(d, -1, DateAdd(mm, 1,  
                         CAST(CAST(GroupYear AS varchar(4)) + '-' + 
                              CAST(GroupMonth AS varchar(2)) + '-' + 
                              CAST(1 AS varchar(1)) As DATETIME))), 101) As PickUpRange, 
      [RowCount]
FROM (
      SELECT District, MONTH(PickUpDate) As GroupMonth, 
                       YEAR(PickUpDate) As GroupYear, 
             Count(*) As [RowCount]
      FROM PDA_COLLECTOR_SCCS
      GROUP BY District, MONTH(PickUpDate), YEAR(PickUpDate)
     ) As derivedTable