Group by quarter (datepart) returns multiple rows with same quarter

不羁岁月 提交于 2019-12-25 00:09:25

问题


I'm trying to return a count for the total number of records in the table HISTORY grouped by their quarter and year. Currently I have:

SELECT DISTINCT (CAST(DATEPART(year, CREATE_DATE) AS char) + ' Qtr' + 
                CAST(DATEPART(quarter, CREATE_DATE) AS char)) AS Period,
       COUNT(ID)
FROM HISTORY
GROUP BY CREATE_DATE
ORDER BY Period;

But I'm getting duplicate rows with the same quarter and year. I'm also getting a total of records counted that's lower than the total records in the table. Here's a sample sql fiddle in case that helps identify the problem.

I wouldn't have thought I'd need to specify DISTINCT in the period column either, but when I don't I get even more dupes... which I'm guessing is part of the same root problem.


回答1:


The problem ist that you are grouping by CREATE_DATE but want to group by year and quarter:

SELECT 
  DATENAME(year, CREATE_DATE) + ' Qtr' + DATENAME(quarter, CREATE_DATE) AS Period,
  COUNT(*) AS NumberOfRecords
FROM HISTORY
GROUP BY DATENAME(year, CREATE_DATE), DATENAME(quarter, CREATE_DATE)
ORDER BY Period;


来源:https://stackoverflow.com/questions/51352832/group-by-quarter-datepart-returns-multiple-rows-with-same-quarter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!