我正在尝试根据表格中的数据创建图表。在图表上,我想显示最近12个月的数据。通过使用以下代码,我当月的数据将与上个月的数据合并。现在说它的12月,所以我想显示最近12月(包括今年12月)的数据。如何更正查询?谢谢您的帮助。
SELECT MONTH(InvoiceDate) AS 'Month', COUNT (DISTINCT InvoiceNo) AS 'Total Invoice' FROM SalesDetail WHERE InvoiceDate > (GETDATE() - 365)
OR MONTH(InvoiceDate) = MONTH(CURRENT_TIMESTAMP)
AND YEAR(InvoiceDate) = (YEAR(CURRENT_TIMESTAMP) - 1)
GROUP BY MONTH(InvoiceDate)
答案 0 :(得分:0)
我想您可以在下面的查询中尝试-
SELECT MONTH(InvoiceDate) AS 'Month', COUNT (DISTINCT InvoiceNo) AS 'Total Invoice'
FROM SalesDetail
WHERE YEAR(InvoiceDate) = (YEAR(CURRENT_TIMESTAMP) - 1)
AND MONTH(InvoiceDate) >= MONTH(CURRENT_TIMESTAMP)
GROUP BY MONTH(InvoiceDate)
所以基本上只比较过去和当前年份,只比较大于或等于当年月份的月份。
答案 1 :(得分:0)
您可以使用以下内容:
SELECT YEAR(InvoiceDate) AS 'Year', MONTH(InvoiceDate) AS 'Month', COUNT (DISTINCT InvoiceNo) AS 'Total Invoice'
FROM SalesDetail
WHERE (
YEAR(InvoiceDate) = YEAR(CURRENT_TIMESTAMP) - 1 AND MONTH(InvoiceDate) >= MONTH(CURRENT_TIMESTAMP)
) OR (
YEAR(InvoiceDate) = YEAR(CURRENT_TIMESTAMP) AND MONTH(InvoiceDate) <= MONTH(CURRENT_TIMESTAMP)
)
GROUP BY YEAR(InvoiceDate), MONTH(InvoiceDate)