我有以下查询,它向我提供了项目的整体状态。我想知道是否有更好的方法来编写相同的查询。
表的示例架构:
CREATE TABLE `test_status`
(
`test_id` int
(11) NOT NULL,
`group_id` int
(11) NOT NULL,
`sub_test_id` int
(11) NOT NULL,
`project_id` int
(11) NOT NULL,
`collection_status` varchar
(20) DEFAULT NULL,
`labeling_status` varchar
(20) DEFAULT NULL,
`upload_status` varchar
(20) DEFAULT NULL,
`upload_date` date DEFAULT NULL,
`disk_number` int
(11) DEFAULT NULL,
`subject_id` varchar
(10) DEFAULT NULL,
`collection_id` varchar
(25) DEFAULT NULL,
`assigned_to` int
(11) DEFAULT NULL,
`assigned_on` date DEFAULT NULL,
`turned_in_date` date DEFAULT NULL,
PRIMARY KEY
(`test_id`,`group_id`,`sub_test_id`,`project_id`));
我的查询
select
(select count(*)
from test_status
where project_id = 7 and collection_status = 'COLLECTED') as collected,
(select count(*)
from test_status
where project_id = 7 and collection_status = 'SCHEDULED') as scheduled,
(select count(*)
from test_status
where project_id = 7 and collection_status = 'CORRUPTED') as corrupted,
(select count(*)
from test_status
where project_id = 7 and collection_status is NULL) as 'not collected',
(select count(*)
from test_status
where project_id = 7 and ((labeling_status = 'GOOD' and (upload_status != 'UPLOADED' or upload_status != 'QUEUED')) or (labeling_status = 'Labeled'))) as 'Labeled',
(select count(*)
from test_status
where project_id = 7 and (labeling_status = 'RAW') or (labeling_status = 'ASSIGNED') ) as 'to be labeled',
(select count(*)
from test_status
where project_id = 7 and labeling_status = 'RE-LABEL') as 'Re-label',
(select count(*)
from test_status
where project_id = 7 and (upload_status = 'UPLOADED' or upload_status = 'QUEUED')) as 'Uploaded',
(select count(*)
from test_status
where project_id = 7 and labeling_status = 'GOOD' and upload_status is null) as 'ready to be uploaded';
答案 0 :(得分:3)
您可以尝试使用条件汇总函数会更好。
在CASE WHEN
中设置条件
SELECT
COUNT(CASE WHEN collection_status = 'COLLECTED' THEN 1 END),
COUNT(CASE WHEN collection_status = 'SCHEDULED' THEN 1 END),
COUNT(CASE WHEN collection_status = 'CORRUPTED' THEN 1 END),
COUNT(CASE WHEN collection_status is NULL THEN 1 END),
COUNT(CASE WHEN ((labeling_status = 'GOOD' and (upload_status != 'UPLOADED' or upload_status != 'QUEUED')) or (labeling_status = 'Labeled'))THEN 1 END),
COUNT(CASE WHEN (labeling_status = 'RAW') or (labeling_status = 'ASSIGNED') THEN 1 END),
COUNT(CASE WHEN labeling_status = 'RE-LABEL' THEN 1 END),
COUNT(CASE WHEN (upload_status = 'UPLOADED' or upload_status = 'QUEUED') THEN 1 END),
COUNT(CASE WHEN labeling_status = 'GOOD' and upload_status is null THEN 1 END)
FROM test_status
WHERE project_id = 7
或者您可以尝试一种更简单的方法,将SUM
(0或1)与bool
的{{1}}
count