你好团队是sql的新手
我有两个像这样的选择查询
select fv.value as primary_hod, count(*) as closed
from artifact a, item i, field_value fv
where i.id=a.id and i.folder_id = 'tracker1127' and fv.id = a.fv_0
and a.close_date is not NULL and i.date_created > i.date_created - INTERVAL '30 days'
group by fv.value;
这是返回
primary_hod | closed
------------------+--------
Sivaramakrishnan | 1
和其他查询
select fv.value as primary_hod, count(*) as Open
from artifact a, item i, field_value fv
where i.id=a.id and i.folder_id = 'tracker1127' and fv.id=a.fv_0
and a.close_date is NULL and i.date_created > i.date_created - INTERVAL '30 days'
group by fv.value;
返回
primary_hod | open
------------------+------
Sivaramakrishnan | 1
Anand | 2
Manav | 1
Prasanna | 1
我想要这样的东西
primary_hod | open | Closed
------------------+------+
Sivaramakrishnan | 1 | 1
Anand | 2 | 0
Manav | 1 | 0
Prasanna | 1 | 0
我尝试过工会和工会,但没有运气请注意这个
答案 0 :(得分:3)
使用CASE
表达式进行条件计数:
select fv.value as primary_hod,
count(case when a.close_date is NULL then 1 end) as open,
count(case when a.close_date is not NULL then 1 end) as closed
from artifact a, item i, field_value fv
where i.id=a.id and i.folder_id = 'tracker1127' and fv.id = a.fv_0
and i.date_created > i.date_created - INTERVAL '30 days'
group by fv.value;
使用现代明确的JOIN
语法重写:
select fv.value as primary_hod,
count(case when a.close_date is NULL then 1 end) as open,
count(case when a.close_date is not NULL then 1 end) as closed
from artifact a
join item i on i.id = a.id
join field_value fv on fv.id = a.fv_0
where i.folder_id = 'tracker1127'
and i.date_created > i.date_created - INTERVAL '30 days'
group by fv.value;
答案 1 :(得分:1)
您可以在子查询中嵌套一个。
SELECT fv.value AS primary_hod, count(*) AS Open, (SELECT count(*) FROM artifact a
INNER JOIN item i ON i.id = a.id
INNER JOIN field_value fv ON fv.id = a.fv_0
WHERE i.folder_id = 'tracker1127'
AND a.close_date IS NOT NULL
AND i.date_created > i.date_created - INTERVAL '30 days'
GROUP BY fv.value) AS Closed
FROM artifact a
INNER JOIN item i ON i.id = a.id
INNER JOIN field_value fv ON fv.id = a.fv_0
WHERE i.folder_id = 'tracker1127'
AND a.close_date IS NULL
AND i.date_created > i.date_created - INTERVAL '30 days'
GROUP BY fv.value;