求一SQL语句

marongc 2010-09-10 04:57:33
单号 付款金额 付款日期
-------------------- --------------------- -----------------------
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
...全文
67 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hao1hao2hao3 2010-09-10
  • 打赏
  • 举报
回复
付款金额是什么类型的?好像不能用空字符,要用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 单号




dawugui 2010-09-10
  • 打赏
  • 举报
回复
--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 单号
hao1hao2hao3 2010-09-10
  • 打赏
  • 举报
回复


;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 单号


百年树人 2010-09-10
  • 打赏
  • 举报
回复
先编个号,再用case when进行行转列
marongc 2010-09-10
  • 打赏
  • 举报
回复
对了,最多就会有三次付款

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧