我的SQL Server数据库中有一个名为PictureCount
的视图。我根据以下查询获取数据 -
with result as
(SELECT CAST(Createddate AS DATE) AS StartDate, COUNT(ServicePictureID) AS TotalPicture
FROM PictureCount
WHERE ProjectID='11' AND
CAST(CreatedDate As DATE) BETWEEN '2014-10-31' AND '2014-12-05'
GROUP BY CAST(Createddate AS DATE)
)
SELECT
(CAST(DATEPART(YYYY, CAST(StartDate AS DATE)) as varchar) + '-' + CAST(DATEPART(MONTH ,CAST(StartDate AS DATE)) AS varchar)) AS StartDate,
TotalPicture
FROM result
数据以下列格式显示 -
但我想要按StartDate
分组的数据。我无法应用GROUP BY
条款。如果有人知道,请告诉我。
提前致谢。
答案 0 :(得分:1)
尝试此查询:
SELECT Cast(Datepart(YEAR, StartDate) AS VARCHAR(4))
+ '-'
+ Cast(Datepart(MONTH, StartDate) AS VARCHAR(2)) AS StartDate,
Count(ServicePictureID) AS TotalPicture
FROM PictureCount
WHERE ProjectID = '11'
AND CreatedDate BETWEEN '2014-10-31' AND '2014-12-06'
GROUP BY Datepart(YEAR, StartDate),Datepart(MONTH, StartDate)
答案 1 :(得分:1)
如果你能用yyyyMM格式而不是yyyy-MM显示数据,那怎么样呢。此查询的功能和转换次数较少。
SELECT Datepart(YEAR, StartDate)*100 + Datepart(MONTH, StartDate) as yyyyMM
, Count(ServicePictureID) AS TotalPicture
FROM PictureCount
WHERE ProjectID = '11'
AND CreatedDate BETWEEN '2014-10-31' AND '2014-12-05'
GROUP BY Datepart(YEAR, StartDate)*100 + Datepart(MONTH, StartDate)