A表
id pid name rept_id(FK)
1   1   张三    1
2   1   李四    1
3   1   李四    2
4   2   张三    1
B表
rept_id(PK)  rept_name
1            一般报表
2            特殊报表查询得出的结果
rept_id rept_name rept_count
1       一般报表     2
2       特殊报表     1查询条件是A表的pid

解决方案 »

  1.   

    select B表.*,count(distinct A表.rept_id) as rept_count
     from A表 left join B表 pn A表.rept_id=B表.rept_id
    group by rept_id(PK),rept_name
      

  2.   


    select b.*,count(distinct a.name) cnt
    from b join a on b.rept_id = a.rept_id
      

  3.   


    select b.*,count(distinct a.name) cnt
    from b join a on b.rept_id = a.rept_id
    group by b.rept_id,rept_name
      

  4.   

    go
    if OBJECT_ID('a')is not null
    drop table a
    go
    create table a(
    id int,
    pid int,
    name varchar(10),
    rept_id int
    )
    go 
    insert a
    select 1,1,'张三',1 union all
    select 2,1,'李四',1 union all
    select 3,1,'李四',2 union all
    select 4,2,'张三',1go
    if OBJECT_ID('b')is not null
    drop table tbl
    go
    create table b(
    rept_id int,
    rept_name varchar(20)
    )
    go
    insert b
    select 1,'一般报表' union all
    select 2,'特殊报表'select b.*,
    COUNT(a.rept_id) as rept_count
    from b left join a 
    on b.rept_id=a.rept_id
    group by b.rept_id,b.rept_name
    order by rept_id/*
    rept_id rept_name rept_count
    1 一般报表 3
    2 特殊报表 1
    */