表TA,
列a char(20),
  b int,
  c int,
  d int,CREATE TABLE [TA](
[a] [char](20) ,
[b] [int] ,
[c] [int] ,
[d] [int] 
) insert into [TA] 
select '12',12,12,12 union all 
select '12',12,12,12 union all 
select '12',12,12,12 union all 
select '13',13,13,13 union all
select '13',13,13,13 union all
select '14',14,14,14 union all
select '1',1,1,1 union all
select '5',5,5,5查询1: select a,sum(b) as sumB,count(*) as Total from TA group by a 
查询2:select a,count(*) as Num from TA where c>2查询1显示字段: a,sumB,Total  
查询2显示字段: a,Num
查询2的结果,字段a的值是查询1的子集
可不可实现 结果为: a,sumB,Total,Num ,如果Num为空显示为0 

解决方案 »

  1.   

    select a,sum(b) as sumB,count(*) as Total,0 as num from TA group by a 
    union all
    select a,0,0,count(*) as Num from TA where c>2 
      

  2.   

    use db_study
    go
    if not object_id('[TA]') is null
       drop table [TA]
    go
    CREATE TABLE [TA](
        [a] [char](20) ,
        [b] [int] ,
        [c] [int] ,
        [d] [int] 

    insert into [TA] 
    select '12',12,12,12 union all 
    select '12',12,12,12 union all 
    select '12',12,12,12 union all 
    select '13',13,13,13 union all
    select '13',13,13,13 union all
    select '14',14,14,14 union all
    select '1',1,1,1 union all
    select '5',5,5,5
    go
    select a,sum(b) as sumB,count(*) as Total,0 as num from TA group by a 
    union all 
    select a,0,0,count(*) as Num from TA where c>2  group by a a sumB Total num
    1        1 1 0
    12       36 3 0
    13       26 2 0
    14       14 1 0
    5        5 1 0
    12       0 0 3
    13       0 0 2
    14       0 0 1
    5        0 0 1(所影响的行数为 9 行)