Warm tip: This article is reproduced from serverfault.com, please click

sql server-SQL查询枢轴,将值移到顶部

(sql server - SQL query pivot, move values to top)

发布于 2020-11-28 11:41:18

我创建了一个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 |
+----------+----------+----------+----------+----------+
Questioner
tutu
Viewed
11
Gordon Linoff 2020-11-28 20:10:24

将你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);

这是小提琴