我有这个问题:
SELECT
count( case when EXISTS (
SELECT *
FROM business_log bl, subject su
WHERE su.ID_SUBJECT = s.ID_SUBJECT
AND bl.id_subject = su.id_subject
AND bl.value = 'Solved'
)
then 1 else null end) num_solved
FROM subject s
一个主题不止一次是可能的......解决了这个问题。在表BUSINESS_LOG中 我想只计算一个主题解决的一行。 由于其他计数,我必须在主查询中仅使用SUBJECT表。
答案 0 :(得分:1)
business_log:
id_business_log id_subject value
1 1 Solved
2 2 Evidented
3 3 Evidented
4 1 Solved
主题
ID_SUBJECT
1
2
3
使用不带CASE的COUNT查询
SELECT
ID_SUBJECT,
(
SELECT count(*)
FROM business_log bl
WHERE bl.id_subject = s.id_subject
AND bl.value = 'Solved'
) as num_solved
FROM subject s
返回
ID_SUBJECT num_solved
1 2
2 0
3 0
包含CASE的原始查询,但没有COUNT
SELECT
ID_SUBJECT,
case when EXISTS (
SELECT *
FROM business_log bl
WHERE bl.id_subject = s.id_subject
AND bl.value = 'Solved'
)
then 1 else null end num_solved
FROM subject s
返回
ID_SUBJECT num_solved
1 1
2 NULL
3 NULL