问题描述:表a1和表a2的表结构相同。说明:一个单位有多种税,同一单位在表a1中出现的tax不会在a2出现(例:表a1中单位1的税1和税2在表a2的单位1里不会出现)
表1:a1
  ID  Unit    tax    price date
   1   单位1   税1  2      2009-3-1
   2   单位1   税2    4      2009-3-1
   3   单位2   税2    15     2009-3-1
   4   单位2   税3    15     2009-3-1
   5   单位3   税1    22     2009-3-1表2:a1
  ID  Unit    tax    price date
   1   单位1   税3  5      2009-3-1
   2   单位1   税4    6      2009-3-1
   3   单位2   税1    7      2009-3-1
   4   单位3   税3    13    2009-3-1
   5   单位4   税5    18    2009-3-1要求得到以下结果:
1.得到2008年3月份各单位下纳税总和的排名。
    Unit    price  
  单位2    37        
  单位3    35        
  单位4    18       
  单位1    17   
2.得到2008年3月份各单位指定税金(显示税金1,税金3)的总和。
  Unit   税金1    税金3    税金总和
   单位1    2        5       7
   单位2    7        15      22
   单位3    22       13      35
   单位4    无       无       无    

解决方案 »

  1.   

    --1.
    select Unit,sum(price) as price
    from
    (
      select * from [表1] union all select * from [表2]
    ) t
    group by Unit
    order by price desc
    /**
    Unit  price       
    ----- ----------- 
    单位2   37
    单位3   35
    单位4   18
    单位1   17(所影响的行数为 4 行)
    **/
      

  2.   

    --1select m.* , px = (select count(1) from 
    (
      select Unit , sum(price) price from a1 where convert(varchar(7),date,120) = '2009-03'
    ) n where n.price > m.price
    ) + 1 from
    (
      select Unit , sum(price) price from a1 where convert(varchar(7),date,120) = '2009-03'
    ) m
      

  3.   

    --2.
    select 
      Unit,
      sum(case [tax] when '税1' then price else 0 end) as 税金1,
      sum(case [tax] when '税3' then price else 0 end) as 税金1,
      sum(case when [tax] in('税1','税3') then price else 0 end) as 税金总和
    from
    (
      select * from [表1] union all select * from [表2]
    ) t
    group by Unit/**
    Unit  税金1         税金1         税金总和        
    ----- ----------- ----------- ----------- 
    单位1   2           5           7
    单位2   7           15          22
    单位3   22          13          35
    单位4   0           0           0(所影响的行数为 4 行)
    **/
      

  4.   

    --2select unit,
      sum(case tax when '税1' then price else 0 end) [税金1],
      sum(case tax when '税3' then price else 0 end) [税金3],
      isnull((select sum(price) from a1 when tax in ('税1' , '税3') and Unit = t.Unit),0) [税金总和]
    from a1 t
    group by unit