我创建了一个PIVOT查询,但是结果很好。我想拉平行,这样可以说并将所有值移到列表的顶部,而将NULLS移到列表的底部。
http://sqlfiddle.com/#!18/7d17d/6
代替这个:
+----------+----------+----------+----------+----------+
| A | B | C | D | E |
+----------+----------+----------+----------+----------+
| Report 1 | (null) | (null) | (null) | (null) |
| (null) | Report 1 | (null) | (null) | (null) |
| (null) | (null) | Report 2 | (null) | (null) |
| Report 3 | (null) | (null) | (null) | (null) |
| (null) | (null) | Report 4 | (null) | (null) |
| (null) | Report 4 | (null) | (null) | (null) |
| (null) | (null) | (null) | Report 4 | (null) |
| (null) | (null) | (null) | (null) | Report 5 |
| (null) | Report 6 | (null) | (null) | (null) |
| (null) | (null) | (null) | (null) | Report 7 |
| (null) | (null) | (null) | (null) | Report 8 |
+----------+----------+----------+----------+----------+
我想创建这样的东西:
+----------+----------+----------+----------+----------+
| A | B | C | D | E |
+----------+----------+----------+----------+----------+
| Report 1 | Report 1 | Report 4 | Report 4 | Report 5 |
| Report 3 | Report 4 | Report 2 | (null) | Report 7 |
| (null) | Report 6 | (null) | (null) | Report 8 |
+----------+----------+----------+----------+----------+
将你ROW_NUMBER()
的数据更改为按数据源进行分区:
ROW_NUMBER() OVER (partition by datasource ORDER BY GETDATE()) AS rn
你的版本为源数据中的每一行分配了一个唯一的编号,这就是为什么要获得该行数的原因。
因此查询为:
set @query = 'SELECT ' + @cols + '
from (select Name, DataSource,
row_number() over (partition by datasource order by getdate()) AS rn
from T
) x
pivot (max(Name) for DataSource in (' + @cols + ')
) p '
execute(@query);
这是小提琴。
谢谢你的工作!在同一行上获得相同的报告名称是否也很简单?
@tut。。。我不确定您的评论是什么意思。也许您应该问一个带有适当样本数据和所需结果的新问题。