我正在使用Oracle数据库,我遇到了从2个结果集中获得一个结果的问题。
我有表CASES
Create table cases (ID varchar(1), date_entered date, sub_category varchar (5));
insert into cases (id, date_entered, sub_category)
values('1', to_date('2012/05/03','yyyy/mm/dd'),'Temp1');
insert into cases (id, date_entered, sub_category)
values('2', to_date('2012/06/01','yyyy/mm/dd'),'Temp2');
insert into cases (id, date_entered, sub_category)
values('3', to_date('2012/03/15','yyyy/mm/dd'),'Temp3');
insert into cases (id, date_entered, sub_category)
values('4', to_date('2012/03/01','yyyy/mm/dd'),'Call1');
insert into cases (id, date_entered, sub_category)
values('5', to_date('2012/03/08','yyyy/mm/dd'),'Call2');
insert into cases (id, date_entered, sub_category)
values('6', to_date('2012/02/20','yyyy/mm/dd'),'Call2');
需要按子类别计算记录,按月计算一次计数包括sub_category:Temp1,Temp2,Temp3 其他计数包括sub_category:Call1,Call2,Call3
我做了query1:
With skills
AS
(
Select sub_category,
date_entered,
extract(MONTH FROM cases.date_entered) as month_entered,
count (*)
from cases
where
SUB_CATEGORY IN('Temp1', 'Temp2', 'Temp3')
group by cases.sub_category, cases.date_entered
order by to_char(cases.date_entered,'MM')
)
select s.month_entered,
count(*)as skill_count
from skills s
group by s.month_entered
ORDER BY CAST(s.month_entered AS INTEGER) ASC
结果:
MONTH_ENTERED SKILL_COUNT
3 1
5 1
6 1
和查询2:
With training
AS
(
Select sub_category,
date_entered,
extract(MONTH FROM cases.date_entered) as month_entered,
count (*)
from cases
where
SUB_CATEGORY IN('Call1', 'Call2', 'Call3')
group by cases.sub_category, cases.date_entered
order by to_char(cases.date_entered,'MM')
)
select t.month_entered,
count(*)as training_count
from training t
group by t.month_entered
ORDER BY CAST(t.month_entered AS INTEGER) ASC
结果:
MONTH_ENTERED TRAINING_COUNT
2 1
3 2
我从这两个查询中得到的结果是:
MONTH_ENTERED SKILL_COUNT TRAINING_COUNT
2 0 1
3 1 2
5 1 0
6 1 0
试过联盟并离开了加入,但没有什么能给我这个结果......
这是sqlfiddle示例http://sqlfiddle.com/#!4/504cd/31
请帮助,紧急,我被困住了! 提前谢谢
桂贵的回答被接受了。 你能帮我解决这个问题还是我需要新的问题? 如果我想在一年中的所有其他月份显示零,哪些不在表格中,我应该在查询中添加什么?答案 0 :(得分:2)
我认为您可以将查询大幅简化为:
Select extract(MONTH FROM cases.date_entered) as month_entered,
sum(case when SUB_CATEGORY IN('Temp1', 'Temp2', 'Temp3') then 1 else 0 end) as Skill_Count,
sum(case when SUB_CATEGORY IN('Call1', 'Call2', 'Call3') then 1 else 0 end) as Skill_Count,
from cases
group by extract(MONTH FROM cases.date_entered)
order by extract(MONTH FROM cases.date_entered)
答案 1 :(得分:2)
SELECT
EXTRACT(MONTH FROM CASES.DATE_ENTERED) AS MONTH_ENTERED,
COUNT (CASE WHEN SUB_CATEGORY IN('Temp1', 'Temp2', 'Temp3') THEN 1 END) SKILL_COUNT,
COUNT (CASE WHEN SUB_CATEGORY IN('Call1', 'Call2', 'Call3') THEN 1 END) TRAINING_COUNT
FROM CASES
GROUP BY EXTRACT(MONTH FROM DATE_ENTERED)
ORDER BY MONTH_ENTERED ASC