费用名称 费用月份  费用  备注水费       1       100    '1'
水费       2       200    '2'
水费       3       300
水费       4       500
水费       5       700    '5'...
水费       12       700需要查询出如下结果
费用名称  一月份  二月份 ...  十二月份 备注
                               
水费      100      200         700     '1'+'2'+5''请问SQL怎么写?

解决方案 »

  1.   

    交叉表用SQL实现不是太理想,可以先把数据统计出来再用程序实现交叉性能更好。
      

  2.   

    --辅助函数CREATE   FUNCTION dbo.f_str(@iname varchar(10))
    RETURNS varchar(2000)
    AS
    BEGIN
    DECLARE @re varchar(2000)
    SET @re=''
    SELECT @re=@re+' '+isnull(备注,'')
    FROM TableName
    WHERE 费用名称=@iname
    RETURN(STUFF(@re,1,1,''))
    END--查询select
    费用名称,
    isnull(sum(case 费用月份 when 1 then 费用 else 0 end),0) as 一月份,
    isnull(sum(case 费用月份 when 2 then 费用 else 0 end),0) as 二月份,
    isnull(sum(case 费用月份 when 3 then 费用 else 0 end),0) as 三月份,
    isnull(sum(case 费用月份 when 4 then 费用 else 0 end),0) as 四月份,
    isnull(sum(case 费用月份 when 5 then 费用 else 0 end),0) as 五月份,
    isnull(sum(case 费用月份 when 6 then 费用 else 0 end),0) as 六月份,
    isnull(sum(case 费用月份 when 7 then 费用 else 0 end),0) as 七月份,
    isnull(sum(case 费用月份 when 8 then 费用 else 0 end),0) as 八月份,
    isnull(sum(case 费用月份 when 9 then 费用 else 0 end),0) as 九月份,
    isnull(sum(case 费用月份 when 10 then 费用 else 0 end),0) as 十月份,
    isnull(sum(case 费用月份 when 11 then 费用 else 0 end),0) as 十一月份,
    isnull(sum(case 费用月份 when 11 then 费用 else 0 end),0) as 十二月份,
    dbo.F_STR(费用名称)
    from
    tablename
    group by
    费用名称--未测试
      

  3.   

    因为你是固定列的,可以这么写,
    declare @t table(费用名称 varchar(10), 一月份 decimal(18,4), 二月份 decimal(18,4),... 备注 varchar(1000))
    insert into @t(费用名称) select 费用名称 from 表update @t set 一月份=(select sum(费用月份) from 表 group by 费用名称 where 费用月份=1 and 费用名称 = @t.费用名称)update @t set 二月份=(select sum(费用月份) from 表 group by 费用名称 where 费用月份=12 and 费用名称 = @t.费用名称)......select * from @t
      

  4.   

    LouisXIV(夜游神) 的不错,支持.
      

  5.   

    你这个是做报表时用的吧,楼上的方法不错,我说一个临时表来实现的方法,
    大概思路是这样:
    1、建一个临时表,14列,分别是[费用],1~12月,[备注],
    2、insert into 临时表 select distinct 费用(架构已经打好)
    3、更新操作:declare cursor cur_update for 
                        select 费用名称,费用月份,费用,备注 from 表1 
                into (cur费用名称,cur费用月份,cur费用,cur备注) 
                update 临时表 set cur费用月份 = cur费用,备注 = cur备注
                where 费用 = cur费用名称
    4、select 语句,drop 临时表这个相当于把横的做好,再插入竖的,然后填充中间的。
      

  6.   

    --辅助函数CREATE   FUNCTION dbo.f_str(@iname varchar(10))
    RETURNS varchar(2000)
    AS
    BEGIN
    DECLARE @re varchar(2000)
    SET @re=''
    SELECT @re=@re+' '+isnull(备注,'')
    FROM TableName
    WHERE 费用名称=@iname
    RETURN(STUFF(@re,1,1,''))
    ENDselect 费用名称,dbo.f_str(费用名称)as 备注 into #re from Tablename group by 费用名称declare @s varchar(8000)
    set @s=''
    select @s=@s+',['+費用月份+']=sum(case 費用月份 when '''+費用月份+''' then 費用 else null end )' from aaaa group by 費用月份 order by 費用月份exec ( 'select a.费用名称+@s+',b.备注 from Tablename a,#re b where a.费用名称=b.费用名称 group by  a.费用名称,b.备注)