Sql server 如何按计数联接表组

Sql server 如何按计数联接表组,sql-server,Sql Server,我有疑问1: 我还有疑问2: 如何通过id将查询1与查询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

我有疑问1:

我还有疑问2:


如何通过id将查询1与查询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
;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
由于您指定了SQL Server,您还可以使用

差不多

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
;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

谢谢Christian GoolhardtHie Adriaan Stander。。我是如何成功地回答你。。。结果是这样的。。id | countall | id | cnt 1 | 2 | 1 | 6我怎么会这样?id | countall | cnt | 1 | 2 | 6 |噢,谢谢。。。我能做到。。。select*from=选择a.id、countall、cnt。。呵呵。。非常感谢Adrian…更改选择*以选择a.ID、a.Count\u All、b.Cnt