0

SQL问题:

我有这个查询:

SELECT MONTHNAME(date) AS month, Year(getdate()) AS Year, COUNT(*) AS monthly_sales_count
FROM orders
WHERE status = 0
AND YEAR(date) = 2012
GROUP BY month;

这给了我每月 2012 年的结果。

如何在一组数据中添加 2011 年的结果,所以我会得到这样的结果:

Month       Year       Monthly_sales_count
december    2012        6576
november    2012        8788
october     2012        7676
september   2012          56
august      2012         345
july        2012        3356
june        2012        6563
may         2012        3245 
april       2012       25234
march       2012         234
february    2012         454
january     2012       24352
december    2011        6576
november    2011        8788
october     2011        7676
september   2011        1313
august      2011        1343
july        2011        2243
june        2011         656
may         2011        3234
april       2011      435345
march       2011       34345
february    2011        2134
january     2011        3412
4

2 回答 2

2
SELECT MONTHNAME(date) AS month, Year(date) AS Year, COUNT(*) AS monthly_sales_count
FROM orders
WHERE status = 0
AND YEAR(date) IN (2011, 2012)
GROUP BY month, year
ORDER BY year, month;

虽然我希望让 WHERE 子句成为 sargable (利用索引)

SELECT MONTHNAME(date) AS month, Year(date) AS Year, COUNT(*) AS monthly_sales_count
FROM orders
WHERE status = 0
    AND date >= '20110101' AND date < '20130101'
GROUP BY month, year;

注意:
您正在做YEAR(GETDATE()),而我假设您实际上想要做YEAR(date)-如果您是故意的,那么将需要有关确切要求的更多信息。

于 2012-12-05T12:41:51.243 回答
0
SELECT MONTHNAME(date) AS month, Year(getdate()) AS Year, 
                COUNT(*) AS monthly_sales_count
FROM orders
WHERE status = 0
AND YEAR(date) = 2012
GROUP BY month
union
SELECT MONTHNAME(date) AS month, Year(getdate()) AS Year, 
                COUNT(*) AS monthly_sales_count
FROM orders
WHERE status = 0
AND YEAR(date) = 2011
GROUP BY month;
于 2012-12-05T12:43:01.137 回答