![](/img/trans.png)
[英]MySQL Query for current year sales by month and previous years sales by month
[英]How can i get current day, current week, current month, current year sales sum in single mysql query?
我已經單獨編寫了以下查詢,但我想在一個查詢中,如何做到這一點,誰能幫忙..?
SELECT IFNULL(SUM(net_amount),0) as current_date FROM orders WHERE is_cancelled = false and business_date = CURRENT_DATE();
SELECT IFNULL(SUM(net_amount),0) as current_week FROM orders WHERE is_cancelled = false and YEARWEEK(business_date) = YEARWEEK(CURRENT_DATE());
SELECT IFNULL(SUM(net_amount),0) as current_month FROM orders WHERE is_cancelled = false and MONTH(business_date) = MONTH(CURRENT_DATE());
SELECT IFNULL(SUM(net_amount),0) as current_year FROM orders WHERE is_cancelled = false and YEAR(business_date) = YEAR(CURRENT_DATE());
您可以使用條件聚合來將所有單獨的 select 語句組合成統一的語句,例如
SELECT SUM(CASE WHEN business_date = CURRENT_DATE()
THEN
net_amount
ELSE
0
END ) AS current_date,
SUM(CASE WHEN YEARWEEK(business_date) = YEARWEEK(CURRENT_DATE())
THEN
net_amount
ELSE
0
END ) AS current_week,
SUM(CASE WHEN MONTH(business_date) = MONTH(CURRENT_DATE())
THEN
net_amount
ELSE
0
END ) AS current_month,
SUM(CASE WHEN YEAR(business_date) = YEAR(CURRENT_DATE())
THEN
net_amount
ELSE
0
END ) AS current_year
FROM orders
WHERE is_cancelled = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.