[英]SQL Query to obtain the maximum value for each unique value in another column
[英]Oracle SQL - Add missing dates into query for each unique value in another column
我正在尝试通过下表在Oracle SQL中进行查询,我的目标是为每个商店添加缺少的天数。
+------------+-------+-------+
| Date | Store | Sales |
+------------+-------+-------+
| 01/01/2018 | A | 20 |
| 01/03/2018 | A | 30 |
| 01/02/2018 | B | 10 |
| 01/03/2018 | B | 40 |
| 01/04/2018 | B | 50 |
| 01/01/2018 | C | 20 |
+------------+-------+-------+
所需输出:
+------------+-------+-------+
| Date | Store | Sales |
+------------+-------+-------+
| 01/01/2018 | A | 20 |
| 01/02/2018 | A | 0 |
| 01/03/2018 | A | 30 |
| 01/04/2018 | A | 0 |
| 01/01/2018 | B | 0 |
| 01/02/2018 | B | 10 |
| 01/03/2018 | B | 40 |
| 01/04/2018 | B | 50 |
| 01/01/2018 | C | 20 |
| 01/02/2018 | C | 0 |
| 01/03/2018 | C | 0 |
| 01/04/2018 | C | 0 |
+------------+-------+-------+
我有4天需要这个SO问题 ,但是我无法使输出看起来像期望的输出。 有任何想法吗?
使用cross join
生成行,然后使用left join
引入数据:
select s.store, d.date, coalesce(t.sales, 0) as sales
from (select distinct store from t) s cross join
(select distinct date from t) d left join
t
on t.store = s.store and t.date = t.date;
一种选择是加入日历表:
WITH calendar AS (
SELECT date '2018-01-01' AS "Date" FROM dual UNION ALL
SELECT date '2018-02-01' FROM dual UNION ALL
SELECT date '2018-03-01' FROM dual UNION ALL
SELECT date '2018-04-01' FROM dual
)
SELECT
c."Date",
s.Store,
COALESCE(t.Sales, 0) AS Sales
FROM calendar c
CROSS JOIN (SELECT DISTINCT Store FROM yourTable) s
LEFT JOIN yourTable t
ON t."Date" = c."Date" AND t.Store = s.Store;
在这里可能需要使用正式的日历表,因为也许您当前的表数据集不包含您希望出现在最终报告中的所有日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.