如何按计数连接表组

时间:2015-03-31 03:56:55

标签: sql-server

我有 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

enter image description here


我还有 query_2

select id, COUNT (*) from tabel_b
where ids <> 'T' and idt ='C'
group by id

如何通过id query_1 加入 query_2

1 个答案:

答案 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