基础数据:
主表 
id 金额 日期
1  200 2009-01-14
2  300 2009-01-14
3  300 2009-01-14从表 
id 主表id 型号 
1  1      2 
2  1      3 
3  2      2 
4  3      2 形成以下查询数据:
日期          型号2 型号3 总金额
2009-01-14   3     1     800求sql写法
  

解决方案 »

  1.   

    参照一下这个
    if object_id('[s]') is not null drop table [s]
    create table [s] (id int,pid int,bm varchar(8))
    insert into [s]
    select 7,2,'单位1' union all
    select 8,2,'单位22' union all
    select 9,2,'单位3333' union all
    select 10,3,'单位1' union all
    select 11,3,'单位22' union all
    select 12,3,'单位22'declare @sql varchar(1000)
    set @sql='select pid'
    select @sql=@sql+',[bm'+ltrim(px)+']=max(case px when '''+ltrim(px)+''' then bm else '''' end)'
    from (select distinct px=(select count(1) from s where pid=a.pid and id<=a.id) from [s] a)a
    set @sql=@sql+' from (select px=(select count(1) from s where pid=a.pid and id<=a.id),* from [s] a)a group by pid'
    exec(@sql)
      

  2.   

    好像不要行列互换吧,型号2,3都是确定的品种我仔细写的sql,如果明细有2条,金额会统计两次,不知道怎么回事
      

  3.   

    select a.日期,sum(case when b.型号=2 then 1 else 0 end) 型号2,
    sum(case when b.型号=3 then 1 else 0 end) 型号3,
    sum(a.金额) 总金额
    from 主表 a join 从表 b on a.id=b.主表id group by a.日期
      

  4.   

    create table 主表(id int,金额 int,日期 datetime)
    insert 主表 values(1,  200, '2009-01-14')
    insert 主表 values(2 , 300 ,'2009-01-14')
    insert 主表 values(3  ,300 ,'2009-01-14')create table 从表(id int,主表id int,型号 int)
    insert 从表 values(1,  1      ,2)
    insert 从表 values(2,  1,      3)
    insert 从表 values(3 , 2 ,     2)
    insert 从表 values(4  ,3  ,    2 )select a.日期,sum(case when b.型号=2 then 1 else 0 end) 型号2,
    sum(case when b.型号=3 then 1 else 0 end) 型号3,
    (select sum(金额) from 主表 where 日期=a.日期) 总金额
    from 主表 a join 从表 b on a.id=b.主表id group by a.日期
    /*
    日期                      型号2         型号3         总金额
    ----------------------- ----------- ----------- -----------
    2009-01-14 00:00:00.000 3           1           800
    */
      

  5.   

    http://blog.csdn.net/htl258/archive/2009/03/01/3947993.aspx