我有 query_1 :
select id,
count(case when no01 ='B' then 1 END) +
count(case when no02='B' then 1 END) +
count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
我还有 query_2 :
select id, COUNT (*) from tabel_b
where ids <> 'T' and idt ='C'
group by id
如何通过id
将 query_1 加入 query_2 ?
答案 0 :(得分:2)
您可以尝试使用子选择。像
这样的东西SELECT *
FROM (
select id,
count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
) a INNER JOIN
(
select id,
COUNT (*) cnt
from tabel_b
where ids <> 'T'
and idt ='C'
group by id
) b ON a.ID = b.ID
看到您指定的SQL Server,您还可以使用Common Table Expression。
像
这样的东西;WITH a AS (
select id,
count(case when no01 ='B' then 1 END) + count(case when no02='B' then 1 END) + count(case when no03='B' then 1 END) as Count_All
From tabel_a
where date ='20150201'
group by id
)
, b as (
select id,
COUNT (*) cnt
from tabel_b
where ids <> 'T'
and idt ='C'
group by id
)
SELECT *
FROm a INNER JOIN
b ON a.ID = b.ID