按行和列分组

时间:2015-04-23 17:08:57

标签: sql oracle oracle11g

我是sql的新手,我有一个我无法解决的问题,我有一个视图,结合来自不同表的信息做不同的操作,基本上,简化,它看起来有点像这样:

Status      Number of Tasks    Number of Delayed Tasks
-------------------------------------------------------
Green                     2                          1
Yellow                    3                          2
Red                       3                          2

我想要实现的是按状态对所有任务进行分组,遵循每个状态下的任务计数,并且列中列出了属于不同状态的所有延迟或准时任务:

Create Table longcodes (
    longcode varchar(20)
    )

Create Table products (
    prodCode char(3)
    )

insert products values('100')
insert products values('111')
insert products values('123')

insert longcodes values ('abc_a_100_test')
insert longcodes values ('asdf_111_bob')
insert longcodes values ('in_0314_123_95pf')
insert longcodes values ('f_100_u')
insert longcodes values ('hihi_111_bye')
insert longcodes values ('in_123_0314_95pf')
insert longcodes values ('a_b__c_d_100_efg')

select * 
from products p 
     join longcodes l on l.longcode like '%_' + p.prodCode + '_%'

我已经尝试复制from子句中的视图并使其仅在where类中选择延迟任务但是它没有给我准确的结果,我不知道还有什么可以尝试。

感谢任何帮助:)

2 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

select status, count(*) as NumTasks,
       sum(case when completion = 'Delayed' then 1 else 0 end) as NumDelayedTasks
from yourview
group by status;

答案 1 :(得分:1)

嘿,你可以使用下面的查询。

WITH sample_data(riskstatus,taskname,completion)
AS
(
SELECT 'Green','Task1','On Time' FROM dual
UNION ALL
SELECT 'Yellow','Task2','Delayed' FROM dual
UNION ALL
SELECT 'Yellow','Task3','On Time' FROM dual
UNION ALL
SELECT 'Green','Task4','Delayed' FROM dual
UNION ALL
SELECT 'Red','Task5','Delayed' FROM dual
UNION ALL
SELECT 'Yellow','Task5','Delayed' FROM dual
UNION ALL
SELECT 'Red','Task5','On Time' FROM dual
UNION ALL
SELECT 'Red','Task5','Delayed' FROM dual
)
SELECT riskstatus,count(taskname),sum(decode(completion,'Delayed',1,0))
FROM sample_data
GROUP BY riskstatus;