我对SQL还是很陌生,并且正在尝试编写查询以查找类似以下情况的逻辑:
wk_id | start_date | end_date | status
----- ---------- ------ ------
1 20160101 20160101 SUCCEEDED
2 20160101 20160101 SUCCEEDED
3 20160101 20160101 SUCCEEDED
4 20160101 20160101 SUCCEEDED
5 20160101 20160101 FAILED
6 20160102 20160102 SUCCEEDED
7 20160102 20160102 SUCCEEDED
8 20160102 20160102 FAILED
9 20160102 20160102 FAILED
10 20160101 20160101 FAILED
11 20160101 20160101 FAILED
因此,三天来提交了一些作品,一些失败了,一些成功了。
我想编写一个查询,该查询返回每天的作品总数,成功的作品和失败的作品。
我肯定做错了,但这就是我的想法。
请指出错误并解释其逻辑。
select
w1.end_date,
w1.status,COUNT(*) as total_instances,
COUNT(*) as as succeeded_instances,
COUNT(*) as as failed_instances
from
work_instances w1 ,
work_instances w2
where
w1.status LIKE 'SUCCEEDED'
and w2.status NOT LIKE 'SUCCEEDED'
and w1.wk_id = w2.wk_id
group by
w1.end_date,w1.status;
答案 0 :(得分:3)
将聚合函数与大小写一起使用
select
w1.end_date,COUNT(*) AS total_work,
sum(case when w1.status='SUCCEEDED' then 1 else 0 end ) as SUCCEEDED_task,
sum(case when w1.status='FAILED' then 1 else 0 end ) as FAILED_task
from
work_instances w1 group by w1.end_date
答案 1 :(得分:1)
也许更优雅的方法是在聚合函数调用中使用FILTER:
WITH work_instances(wk_id, start_date, end_date, status) AS (
VALUES
(1, '20160101'::DATE, '20160101'::DATE, 'SUCCEEDED'),
(2, '20160101', '20160101', 'SUCCEEDED'),
(3, '20160101', '20160101', 'SUCCEEDED'),
(4, '20160101', '20160101', 'SUCCEEDED'),
(5, '20160101', '20160101', 'FAILED'),
(6, '20160102', '20160102', 'SUCCEEDED'),
(7, '20160102', '20160102', 'SUCCEEDED'),
(8, '20160102', '20160102', 'FAILED'),
(9, '20160102', '20160102', 'FAILED'),
(10, '20160101', '20160101', 'FAILED'),
(11, '20160101', '20160101', 'FAILED')
)
SELECT
end_date,
count(*) AS total_instances,
count(*) FILTER (WHERE status = 'SUCCEEDED') AS succeeded_instances,
count(*) FILTER (WHERE status = 'FAILED') AS failed_instances
FROM
work_instances
GROUP BY
end_date
答案 2 :(得分:0)
听起来像您可以使用条件聚合。
<mat-select *selectedType placeholder="Type" formControlName="type">
<mat-option *ngFor="let type of typeData" [value]="type.Type_id">
{{type.type_name}}
</mat-option>
</mat-select>
如果状态为正确的SELECT end_date,
count(*) total_instances,
count(CASE
WHEN status = 'SUCCEEDED' THEN
1
END) succeeded_instances,
count(CASE
WHEN status = 'FAILED' THEN
1
END) failed_instances
FROM work_instances
GROUP BY end_date;
将仅返回一个非null值(此处为1,但可能不是null)。而且CASE
不会只计算非空值。