您好我有这样的查询返回过去6个月的注册数据,但是只有至少有1个注册才能显示数据,如何显示没有注册的月份?我知道我可能要对这一行做点什么:
LEFT(CONVERT(varchar, issuedate, 112), 6) BETWEEN
LEFT(CONVERT(varchar, DATEADD(MM, -6, GETDATE()), 112), 6) AND
LEFT(CONVERT(varchar, GETDATE(), 112), 6)
感谢。
SELECT
DateName(month,issuedate) + ' ' + CAST(Year(issuedate) as Char(4)) as IssueDate,
COUNT(distinct m.ID) AS SignUps
FROM
Member m
INNER JOIN
Card c ON m.ID = c.MemberID
WHERE
m.Deletedby is null
AND c.Deletedby is null
AND LEFT(CONVERT(varchar, issuedate, 112), 6) BETWEEN
LEFT(CONVERT(varchar, DATEADD(MM, -6, GETDATE()), 112), 6)
AND LEFT(CONVERT(varchar, GETDATE(), 112), 6)
GROUP BY
DateName(month, issuedate) + ' ' + CAST(Year(issuedate) AS Char(4)), CAST(CAST(YEAR(issuedate) AS VARCHAR) + '/'+ CAST(MONTH(issuedate) AS VARCHAR) +'/1' AS DateTime)
答案 0 :(得分:2)
<强>观察:强>
1.表名并不意味着它们是如何连接的
2.使用你曾经使用过的函数永远不会使用正确的索引
3.所有列引用都应该由表别名限定,以使代码易于理解
4. getdate()是一个非确定性函数,导致错误的查询计划。将日期传递到sp。
假设当某个成员注册该卡时,会创建Card表中的条目: -
SELECT
<month_year_string> as IssueDate,
COUNT(distinct c.memberid) AS SignUps
FROM
Member m
lEFT OUTER JOIN
Card c ON m.ID = c.MemberID AND c.Deletedby is null
WHERE
m.Deletedby is null
AND c.issuedate BETWEEN DATEADD(MM, -6, GETDATE()) AND GETDATE()
GROUP BY <month_year_string>