我使用 lag() 能夠正確顯示年銷售額差異。但是,由于某些類別在某些月份缺少銷售,因此滯后不會到達正確的月份。
我目前使用以下代碼:
SELECT extract(YEAR_MONTH from processed_at) as 'Year_Month',
product_type,
sum(`Revenue`) as 'Revenue',
lag(sum(`Revenue`),12) over (partition by product_type order by extract(year_month from processed_at)) as 'YoY Revenue'
FROM dashboard
GROUP by 1,2
ORDER by 1 desc;
例如,下表將無法正確顯示 2022_01 YoY Gloves 的收入(我們希望看到 2021_01 銷售額的數字 1180),因為 Gloves 在前幾個月中沒有任何銷售。因此它將無法正確倒數到 2021_01(由 lag() 設定的 12 個月前)
------------ -------------- --------- -------------
| Year_Month | Product_Type | Revenue | YoY Revenue |
------------ -------------- --------- -------------
| 202201 | Gloves | 180 | 1500 |
------------ -------------- --------- -------------
| 202201 | Jackets | 210 | 3900 |
------------ -------------- --------- -------------
| 202201 | Pants | 310 | 1820 |
------------ -------------- --------- -------------
| 202112 | Jackets | 500 | 600 |
------------ -------------- --------- -------------
| 202112 | Pants | 600 | 700 |
------------ -------------- --------- -------------
| 202101 | Gloves | 1180 | 1600 |
------------ -------------- --------- -------------
| 202101 | Jackets | 3900 | 4000 |
------------ -------------- --------- -------------
| 202101 | Pants | 1820 | 1900 |
------------ -------------- --------- -------------
是否有一種聰明的方法來顯示一個 product_type 每個月,即使它沒有進行任何銷售并且不能按該月分組?
(在 MySQL 中撰寫)
uj5u.com熱心網友回復:
你需要這樣的東西:
WITH
cte1 AS ( SELECT DISTINCT Year_Month
FROM table ),
cte2 AS ( SELECT DISTINCT Product_Type
FROM table )
SELECT Year_Month,
Product_Type,
COALESCE(table.Revenue, 0) Revenue,
COALESCE(table.YoY, 0) YoY
FROM cte1
CROSS JOIN cte2
NATURAL JOIN table
這將填補您的“漏洞”(如果零不安全,請調整缺失行的值)。在此之后,您可以計算您需要的所有內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/407531.html
標籤:
上一篇:如何在8.0上保留mysql5.6GROUPBY規則?
下一篇:MySQL查詢匯總
