单号 付款金额 付款日期
-------------------- --------------------- -----------------------
107883 1000.00 2010-09-10 15:40:59.250
107883 1000.00 2010-09-11 15:47:47.000
107883 118.69 2010-09-12 13:47:47.000我的是这样的
单号   付款金额 付款日期               付款金额 付款日期               付款金额 付款日期
107883 1000.00 2010-09-10 15:40:59.250 1000.00 2010-09-11 15:47:47.000 118.69 2010-09-12 13:47:47.000

解决方案 »

  1.   

    先编个号,再用case when进行行转列
      

  2.   

    ;with cte as
    (
    select row_number() over(partition by 单号 order by getdate()) id,* 
    from tb
    )select 单号,max(case when id = 1 then 付款金额 else '' end) 付款金额,
    max(case when id = 1 then 付款日期 else '' end) 付款日期,
    max(case when id = 2 then 付款金额 else '' end) 付款金额1,
    max(case when id = 2 then 付款日期 else '' end) 付款日期1,
    max(case when id = 3 then 付款金额 else '' end) 付款金额2,
    max(case when id = 3 then 付款日期 else '' end) 付款日期2
    from cte
    group by 单号
      

  3.   

    --sql 2000
    select 单号,
           max(case px when 1 then 付款金额 end) 付款金额1,
           max(case px when 1 then 付款日期 end) 付款日期1,
           max(case px when 2 then 付款金额 end) 付款金额2,
           max(case px when 2 then 付款日期 end) 付款日期2,
           max(case px when 3 then 付款金额 end) 付款金额3,
           max(case px when 3 then 付款日期 end) 付款日期3
    from
    (
      select t.* , px = (select count(1) from tb where 单号 = t.单号 and 付款日期 < t.付款日期) + 1 from tb t
    ) m
    group by 单号--sql 2005
    select 单号,
           max(case px when 1 then 付款金额 end) 付款金额1,
           max(case px when 1 then 付款日期 end) 付款日期1,
           max(case px when 2 then 付款金额 end) 付款金额2,
           max(case px when 2 then 付款日期 end) 付款日期2,
           max(case px when 3 then 付款金额 end) 付款金额3,
           max(case px when 3 then 付款日期 end) 付款日期3
    from
    (
      select t.* , px = row_number() over(partition by 单号 order by 付款日期) from tb t
    ) m
    group by 单号
      

  4.   

    付款金额是什么类型的?好像不能用空字符,要用0 代替
    ;with cte as
    (
        select row_number() over(partition by 单号 order by getdate()) id,* 
        from tb
    )select 单号,max(case when id = 1 then 付款金额 else 0 end) 付款金额,
    max(case when id = 1 then 付款日期 else 0 end) 付款日期,
    max(case when id = 2 then 付款金额 else 0 end) 付款金额1,
    max(case when id = 2 then 付款日期 else 0 end) 付款日期1,
    max(case when id = 3 then 付款金额 else 0 end) 付款金额2,
    max(case when id = 3 then 付款日期 else 0 end) 付款日期2
    from cte
    group by 单号