有张表
          年       月      数量    名称
2007      3 20      鼠标        
2007      4 26      鼠标        
2008      1 21      光驱        
2007      3 24      硬盘       
2007      4 26      硬盘 要查询2007年4月比2007年3月数量大20%名称列出来  
效果如下:
名称   年   4月数量    3月数量  
鼠标  2007    26          20

解决方案 »

  1.   

    declare @a table(年 int, 月 int, 数量 int, 名称 varchar(19))
    insert @a select 2007 ,3 ,20 ,'鼠标'
    union all select 2007 ,4 ,26 ,'鼠标' 
    union all select 2008 ,1 ,21 ,'光驱'
    union all select 2007 ,3 ,24 ,'硬盘' 
    union all select 2007 ,4 ,26 ,'硬盘'select * from
    (
    select 名称,年,
    [4月]=sum(case when 月=4 then 数量 else 0 end),
    [3月]=sum(case when 月=3 then 数量 else 0 end)
    from @a group by 名称,年
    ) aa
    where [4月]>[3月]*1.2
      

  2.   

    --result
    /*
    名称      年      4月    3月          
    -------- ----- -----  ----- 
    鼠标      2007   26    20 (所影响的行数为 1 行)
    */
      

  3.   

    create table test(年 int,月 int,数量 int,名称 varchar(10))
    insert test select 2007,3,20,'鼠标'
    union all select 2007,4,26,'鼠标'
    union all select 2008,1,21,'光驱'
    union all select 2007,3,24,'硬盘'
    union all select 2007,4,26,'硬盘'select 名称,年,[4月数量]=sum(case when 月=4 then 数量 end),
    [3月数量]=sum(case when 月=3 then 数量 end)
    from test
    group by 名称,年
    having
    (sum(case when 月=4 then 数量 end)*1.0
    -sum(case when 月=3 then 数量 end))/sum(case when 月=3 then 数量 end)=0.3名称         年           4月数量        3月数量        
    ---------- ----------- ----------- ----------- 
    鼠标         2007        26          20
      

  4.   

    改下:
    select 名称,年,[4月数量]=sum(case when 月=4 then 数量 end),
    [3月数量]=sum(case when 月=3 then 数量 end)
    from test
    group by 名称,年
    having
    (sum(case when 月=4 then 数量 end)*1.0
    -sum(case when 月=3 then 数量 end))/sum(case when 月=3 then 数量 end)>0.2