我想根据月份过滤记录。要求是以月为单位的“已完成,待处理,已启动等”状态。这是我的查询,但我得到重复的记录。
SELECT distinct convert(varchar(7), w.ExpectedStartDate, 126) AS StatusOfMonth, COUNT(w.StatusTypeId) AS StatusCount, w.StatusTypeId, st.StatusTypeName FROM Table1 w LEFT OUTER JOIN StatusType st ON st.StatusTypeId = w.StatusTypeId WHERE CONVERT(VARCHAR(20), w.ExpectedStartDate, 103) BETWEEN '10/01/2011' AND '14/04/2011' GROUP BY ExpectedStartDate, w.StatusTypeId, st.StatusTypeName
请参阅图片以澄清我想要的内容。请让我知道如何才能得到正确的结果。
答案 0 :(得分:4)
看起来像您按日期分组,而不是按月或按月状态分组 分组
DATEPART(M, ExpectedStartDate)
或
convert(varchar(7), w.ExpectedStartDate, 126)
而不仅仅是ExpectedStartDate
修改强>
回应评论: 试着摆脱
convert(varchar(7), w.ExpectedStartDate, 126) AS StatusOfMonth
并尝试这样:
SELECT
convert(varchar, datepart(yyyy, w.ExpectedStartDate)) + '-' + CONVERT(varchar(3), DATENAME(month, w.ExpectedStartDate)),
w.StatusTypeId,
st.StatusTypeName,
COUNT(w.StatusTypeId) AS StatusCount
FROM
Table1 w LEFT OUTER JOIN
StatusType st ON st.StatusTypeId = w.StatusTypeId
WHERE
w.ExpectedStartDate BETWEEN '1/10/2011' AND '04/14/2011'
GROUP BY
datepart(M, w.ExpectedStartDate),
datepart(yyyy, w.ExpectedStartDate),
w.StatusTypeId,
st.StatusTypeName