日期:2014-05-17  浏览次数:20429 次

SQL合并多行(N)数据成(1-N)行
本帖最后由 talhanwenhui 于 2012-11-08 15:33:35 编辑 各位技术达人,大家好。
我遇到以下问题:

环境: SQL Server 2005
请教一个问题,我使用pivot方法,进行行转列,得到以下结果


现在想通过一种方法,尽量使行数减少,同时查看也更方便,如下图,请大家帮帮忙,怎么通过SQL合并好?谢谢

------最佳解决方案--------------------
select ISNULL(a.编号,isnull(b.编号,isnull(c.编号,ISNULL(d.编号,e.编号)))),各个时间点补全...
from TB1 as a full join TB2 as b on a.编号=b.编号 and a.rowid=b.rowid
full join TB3 as c on on a.编号=c.编号 and a.rowid=c.rowid
full join TB3 as d on on a.编号=d.编号 and a.rowid=d.rowid
full join TB3 as e on on a.编号=e.编号 and a.rowid=e.rowid
------其他解决方案--------------------
select 编号 ,max(字段)
from tb
group by 编号

在你动态的时候用上面的格式
------其他解决方案--------------------
引用:
SQL code123select 编号 ,max(字段)from tbgroup by 编号
在你动态的时候用上面的格式

有多行的情况,max解决不了
------其他解决方案--------------------
引用:
引用:SQL code123select 编号 ,max(字段)from tbgroup by 编号
在你动态的时候用上面的格式
有多行的情况,max解决不了


是的,不可以。
------其他解决方案--------------------
这种情况,应该按照后面每个字段生成一个包含行号的临时表 (5个),然后5个表 full join 就可以了。
稍有点复杂,不知道哪位另有高见
------其他解决方案--------------------
引用:
这种情况,应该按照后面每个字段生成一个包含行号的临时表 (5个),然后5个表 full join 就可以了。
稍有点复杂,不知道哪位另有高见



我试过了,无法得到正确结果。不知道是不是我的测试方法有问题吗?
------其他解决方案--------------------
不可能啊 ,此思路不会有问题的。
------其他解决方案--------------------
这是其中一个临时表:
 select 编号,[14:00],ROW_NUMBER() over(partition by 编号 order by [14:00]) as rowid
 from TB
 where not [14:00] is null
 group by 编号,[14:00]

------其他解决方案--------------------
引用:
这是其中一个临时表:
SQL code1234 select 编号,[14:00],ROW_NUMBER() over(partition by 编号 order by [14:00]) as rowid from TB where not [14:00] is null group by 编号,[14:00]


这么多个临时表如何join呢?
------其他解决方案--------------------
引用:
select ISNULL(a.编号,isnull(b.编号,isnull(c.编号,ISNULL(d.编号,e.编号)))),各个时间点补全...
from TB1 as a full join TB2 as b on a.编号=b.编号 and a.rowid=b.rowid
full join TB3 as c on on a.编号=c.编号 and a.row……


我测试了一下,这个把完全的相同编号的,合并为一行了,请看我要的合并效果。
比如
编号     14:00      15:00
1           a         b