问题
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