问题
From this query :
select LastStateS='LastStateS1and2'
, count(s.LastState) as sumS,
LasteStateE='LastStateE1and2'
, count(e.LastState) as sumE
from table1 t1
join table2 t2
on t1.ID = t2.ID
join (select LastState
,count(LastState) as sum
from table1
where ID = X
and LastState = 1
or LastState = 2
group by LastState
) s
on s.LastState = t1.LastState
join (select LastState
,count(LastState) as sum
from table1
where ID = X
and LastState = 3
or LastState = 4
group by LastState
) e
on e.LastState = t1.LastState
I can't retrieve the sum of both my "laststate" condition. All I have as result is my two columns empty. Thanks in advance.
回答1:
I am not sure why you are doing some things in this query that are not used, like count(LastState)
in your sub-queries.
I think this is all you need for the results you are looking for:
select
LastStateS ='1 and 2'
, countS = sum(case when t1.LastState in (1,2) then 1 else 0 end)
, LasteStateE ='3 and 4'
, countE = sum(case when t1.LastState in (3,4) then 1 else 0 end)
from table1 t1
inner join table2 t2 on t1.id = t2.id and t1.id = X
To get your original query to return the results you want, you need to use left joins for the subqueries:
select
LastStateS='LastStateS1and2'
, count(s.LastState) as sumS
, LasteStateE='LastStateE1and2'
, count(e.LastState) as sumE
from table1 t1
inner join table2 t2 on t1.ID = t2.ID
left join (
select
LastState
, count(LastState) as sum
from table1
where ID = X
and LastState = 1
or LastState = 2
group by LastState
) s
on s.LastState = t1.LastState
left join (
select
LastState
, count(LastState) as sum
from table1
where ID = X
and LastState = 3
or LastState = 4
group by LastState
) e
on e.LastState = t1.LastState
Also note, as @WEI_DBA points out in their comment, you may have unintended consequences from using where ID = X and LastState = 3 or LastState = 4
instead of where ID = X and (LastState = 3 or LastState = 4)
.
来源:https://stackoverflow.com/questions/41746714/retrieve-multiple-sum-columns-of-sub-queries