[英]Using Lag() when a partition is missing
我使用 lag() 能夠正確顯示年銷售額差異。 但是,由於某些類別在某些月份缺少銷售,因此滯后不會 go 到正確的月份。
我目前使用以下代碼:
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 年 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 中編寫)
你需要這樣的東西:
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
這將填補您的“漏洞”(如果零不安全,請調整缺失行的值)。 在此之后,您可以計算您需要的所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.