有个表    table      
    
id        name     year       num
1          a        1992        3
2          b        1982        4
3          c        1985        5
4          a        1993        3 
5          c        1995        5
6          a        1988        5
统计查询出 name  1980年至1990年 num 种和  1990至2000 num 种合  2000到2010 num中和   显示出的   a          5                       6                0
           b          4                       0                0
           c          5                       5                0怎么实现 

解决方案 »

  1.   

    select name , 
           sum(case when year between 1980 and 1990 then num else 0 end) [1980-1990],
           sum(case when year between 1991 and 2000 then num else 0 end) [1991-2000],
           sum(case when year between 2001 and 2010 then num else 0 end) [2001-2010]
    from tb
    group by name
      

  2.   

    create table tb(id int,name varchar(10),[year] int,num int)
    insert into tb select 1,'a',1992,3
    insert into tb select 2,'b',1982,4
    insert into tb select 3,'c',1985,5
    insert into tb select 4,'a',1993,3
    insert into tb select 5,'c',1995,5
    insert into tb select 6,'a',1988,5
    go
    select name,sum(case when [year] between 1980 and 1989 then num else 0 end)[1980-1989],
    sum(case when [year] between 1990 and 1999 then num else 0 end)[1990-1999],
    sum(case when [year] between 2000 and 2009 then num else 0 end)[2000-2009]
    from tb group by name
    /*
    name       1980-1989   1990-1999   2000-2009
    ---------- ----------- ----------- -----------
    a          5           6           0
    b          4           0           0
    c          5           5           0(3 行受影响)*/
    go
    drop table tb
      

  3.   


    create table tb(id int,name varchar(10),year int,num int)
    insert into tb values(1 ,'a', 1992 ,3)
    insert into tb values(2 ,'b', 1982 ,4)
    insert into tb values(3 ,'c', 1985 ,5)
    insert into tb values(4 ,'a', 1993 ,3 ) 
    insert into tb values(5 ,'c', 1995 ,5)
    insert into tb values(6 ,'a', 1988 ,5)
    goselect name , 
           sum(case when year between 1980 and 1990 then num else 0 end) [1980-1990],
           sum(case when year between 1991 and 2000 then num else 0 end) [1991-2000],
           sum(case when year between 2001 and 2010 then num else 0 end) [2001-2010]
    from tb
    group by name
    drop table tb/*
    name       1980-1990   1991-2000   2001-2010   
    ---------- ----------- ----------- ----------- 
    a          5           6           0
    b          4           0           0
    c          5           5           0(所影响的行数为 3 行)
    */
      

  4.   


    这个year 是按时间的 你这个是按int型的 我回去一是 换成datetime 查询统计 是01号的时候不好使  我用的是 
    sql2000