我在Access数据库中有一个名为PDA_COLLECTOR_SCCS
的表,我想查询每District
个PickupDate
的行数。 District
是一个字符串,表示客户端的区域,PickupDate
是服务订单完成的时间。 PickupDate
格式为mm/d/yyyy
。从10/1/2007
开始到today
。
例如,每个地区的每个月都应该有一个整数输出,即DistrictName, EV
,Date Range 10/1/2007 - 10/31/2007
,RowCount, 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)
此查询返回每个区每天的行数,如何更改此值以返回每月每月的行数,即10/1 / 2007-10 / 31/2007
答案 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