create table z1
(
id varchar(10),
success int
)create table z2
(
id varchar(10)
)insert into z2 values('1')
insert into z2 values('2')
insert into z2 values('3')
insert into z2 values('4')
insert into z2 values('5')insert into z1 values('1',1)
insert into z1 values('2',1)
insert into z1 values('1',1)
insert into z1 values('5',1)
insert into z1 values('1',1)select * from z1
select * from z2select id,sum(success) as total from z1
group by id
这样查显示出来的结果是:
id total
1  3 
2  1
5  1我要显示这样的结果该如何写:
id total
1  3 
2  1
5  1
3  0
4  0
即把z1表中没有纪录,但是在z2表中存在的id号显示总纪录为0

解决方案 »

  1.   


    select z2.id ,isnull(count(z1.success),0) from z1 right join z2 on z1.id=z2.id
    group by z2.id
    order by isnull(count(z1.success),0) desc
    ---------------------------
    1 3
    2 1
    5 1
    3 0
    4 0
      

  2.   

    select z2.id,count(z1.id) as [total] from z2 left join z1 on z1.id=z2.id group by z2.id
      

  3.   

    create table z1
    (
    id varchar(10),
    success int
    )create table z2
    (
    id varchar(10)
    )insert into z2 values('1')
    insert into z2 values('2')
    insert into z2 values('3')
    insert into z2 values('4')
    insert into z2 values('5')insert into z1 values('1',1)
    insert into z1 values('2',1)
    insert into z1 values('1',1)
    insert into z1 values('5',1)
    insert into z1 values('1',1)select * from z1
    select * from z2
    go
    select z2.id ,isnull(count(z1.success),0) from z1 right join z2 on z1.id=z2.id
    group by z2.id
    order by isnull(count(z1.success),0) desc
    drop table z1,z2
    go
    /*id                     
    ---------- ----------- 
    1          3
    2          1
    5          1
    3          0
    4          0*/
      

  4.   

    create table z1
    (
    id varchar(10),
    success int
    )create table z2
    (
    id varchar(10)
    )insert into z2 values('1')
    insert into z2 values('2')
    insert into z2 values('3')
    insert into z2 values('4')
    insert into z2 values('5')insert into z1 values('1',1)
    insert into z1 values('2',1)
    insert into z1 values('1',1)
    insert into z1 values('5',1)
    insert into z1 values('1',1) 
    select z2.id,isnull(sum(z1.success),0) as total from z2 left join z1  on z1.id = z2.id
    group by z2.id 
    id         total
    ---------- -----------
    1          3
    2          1
    3          0
    4          0
    5          1