我正在尝试通过下表在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 |
+------------+-------+-------+
我有this SO question所需的4天时间,但是我无法使输出看起来像期望的输出。有什么想法吗?
答案 0 :(得分:0)
使用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;
答案 1 :(得分:0)
一种选择是加入 calendar 表:
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;
在这里可能需要使用正式的日历表,因为您当前的表数据集可能不包含您希望出现在最终报告中的所有日期。