我有一些问题在做一个典型的报告风格SQL,我希望有经验的人可以提供帮助。
我有以下表格
产品
product_defects
日历
我想要的是能够生成一份报告,概述每天与每个产品类别相关的高/中/低缺陷的数量,例如 - 即使在特定日期的product_defect中可能不存在数据,在哪种情况下它应该返回0.示例:
product_category |日期|高|中|低
1 2012-10-01 1 5 6
2 2012-10-01 2 4 3
3 2012-10-01 1 5 6
1 2012-10-02 0 0 0
2 2012-10-02 2 4 3
3 2012-10-02 1 5 6
...
到目前为止我所做的是:
我已经在这几天打了个招呼,希望有人可以提供帮助。
谢谢
答案 0 :(得分:1)
您需要从产品和日期的所有组合开始,然后加入缺陷:
select p.product_category, c.date,
coalesce(SUM(high_priority), 0) as high_priority,
coalesce(SUM(med_priority), 0) as med_priority,
coalesce(SUM(low_priority), 0) as low_priority
from product p cross join
calendar c left outer join
product_defects pd
on pd.product_id = p.product_id and
pd.date = c.date
group by p.product_category, c.date
order by 2, 1
(注意:这是未经测试的,因此可能存在语法错误。)
答案 1 :(得分:1)
因此,这使用子工厂查询子句(cte
)来聚合每天的每个类别的所有缺陷。我用这个结构使逻辑更清晰;还有其他方法可以做到这一点。然后将子查询外部连接到日历表。
with cte as
( select p.product_category
, d.defect_date
, sum(pd.high_priority) as high_priority
, sum(pd.med_priority) as med_priority
, sum(pd.low_priority) as low_priority
from product p
join product_defect pd
on (pd.product_id = p.product_id )
group by p.product_category
, d.defect_date )
select cte.product_category
, cal.date
, nvl(cte.high_priority, 0) as high_priority
, nvl(cte.med_priority, 0) as med_priority
, nvl(cte.low_priority, 0) as low_priority
from calendar cal
left outer join cte
on cal.date = cte.defect_date
order by cte.product_category
, cal.date
答案 2 :(得分:0)
仅限日历表示例。将从-24(2年)的月数增加到任何数字 - 复制/粘贴代码:
-- 2 years back by date --
SELECT TRUNC(SYSDATE, 'YEAR') - LEVEL AS mydate
FROM dual
CONNECT BY LEVEL <= TRUNC(SYSDATE, 'yy') - TRUNC(Add_Months(SYSDATE, -24), 'yy')
/
添加更多日期:
-- 2 years back by date and week --
SELECT mydate
, TRUNC(mydate, 'iw') wk_starts
, TRUNC(mydate, 'iw') + 7 - 1/86400 wk_ends
, TO_NUMBER (TO_CHAR (mydate, 'IW')) ISO_wk#
FROM
(
SELECT TRUNC(SYSDATE, 'YEAR') - LEVEL AS mydate
FROM dual
CONNECT BY LEVEL <= TRUNC(SYSDATE, 'yy') - TRUNC(Add_Months(SYSDATE, -24), 'yy')
)
/
发布创建表并插入脚本以回答其余问题或使用sqlfiddle ...