select t1.partname,t1.type,price1,price2,price3 
from 
(select partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end type,sum(price) price1 from table1 group by partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end) t1
inner join 
(select partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end type,sum(price) price1 from table1 group by partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end where left(convert(varchar,paydate,112),6)=left(convert(varchar,getdate(),112),6)) t2
on t1.partname=t2.partname and t1.type=t2.type
inner join 
(select partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end type,sum(price) price1 from table1 group by partname,case type when 1 then '1' when 2 then '2/3' when 3 then '2/3 else 'others' end where partname<left(convert(varchar,dateadd(mm,1,getdate()),112),6)+'01') t3
on t1.partname=t3.partname and t1.type=t3.type
union
select s1.partname,s1.type,price1,price2,price3 
from 
(select partname,'' type,sum(price) price1 from table1 group by partname) s1
inner join 
(select partname,'' type,sum(price) price1 from table1 group by partname where left(convert(varchar,paydate,112),6)=left(convert(varchar,getdate(),112),6)) s2
on s1.partname=s2.partname
inner join 
(select partname,'' type,sum(price) price1 from table1 group by partname where partname<left(convert(varchar,dateadd(mm,1,getdate()),112),6)+'01') s3
on s1.partname=s3.partname

解决方案 »

  1.   

    上述t2,s2中的price1应为price2;
    上述t3,s3中的price1应为price3;
      

  2.   

    to gerard2008(gerard)
      你的题目也好难看懂!
      

  3.   

    看看t1、t2、t3很想象,s1、s2、s3很想象就明白70%了!看看t1、t2、t3的inner join 提供结果中的price1、price2、price3三个横向值(这就是交叉报表)就明白90%。剩下10%就是缘分喽!
      

  4.   

    上述t2,s2中的price1应为price2;
    上述t3,s3中的price1应为price3;
      

  5.   

    刚又回来看了一下,又发现缺少几个'号和列别名type。呵呵!自己修改吧!
      

  6.   

    怎么每回回来看一眼都能发现错误呢?看来真是不堪回首呀!又发现 paydate 给写成 partname 喽!
      

  7.   

    临时表?视图?表型函数?看不出比那个SQL查询清楚呀?那些所谓的更加清楚和更快的方法,不就是把 3-5行写一段,7-11 行写一段,14-17行写一段,22行写一段,24-26行写一段,29-31行写一段,然后在把1、2、3连接起来,然后再把4、5、6段连接起来,然后再把最后两段和起来,这简直就是多此一举,代码更多,模块看起来也更混乱。
      

  8.   

    早上上班就看到了这么多回复,很感谢w_rose(w_rose) ,我准备调试一下
      

  9.   

    没什么好办法,你只能用每一个子查询查询出一笔记录,然后再把他们组成行,然后在用UNION把这些行合并到一起。真的好麻烦还有一个办法稍微聪明点,但求不出你要求的最后一行(总和,总和,总和)
    就是用CASE把TYPE分组如果是1分到第一组,2、3分到第二组,其他时候分到第三组
    然后GROUP BY这个分组
    举个例子
    SELECT NEWCOL,SUM(CASE WHEN paydate IS 当前月份 THEN PRICE),。
    FROM TABLE1
    GROUP BY CASE TYPE WHEN 1 THEN 1
                       WHEN 2 THEN 2
                       WHEN 3 THEN 2
                       ELSE 3
                       END
      

  10.   

    w_rose(w_rose) 
    hillhx(曾经的曾经) 
    各50分