重新排列数据透视表中的值

时间:2014-03-10 21:42:58

标签: sql sql-server null pivot

我正在使用SQL Server 2012,自学成才,对任何错误/错误表示抱歉。

我有一个表,我有一个数据透视表,结果表有空值,如下所示:

Pepsi    Coke    Gatorade
--------------------------
Vanilla  NULL    NULL
Cherry   NULL    NULL
NULL     Vanilla NULL
NULL     Cherry  NULL
NULL     NULL    Lime
NULL     NULL    Fruit Punch
NULL     NULL    Grape

我的问题是,是否有办法重新排列表格,以便非空行显示在各自列的顶部,这样如果另一个用户要添加不同类型的饮料,例如water,查询将自动对新添加的列进行排序。如果无法做到这一点,那么我们将不胜感激。

所需结果的一个例子如下:

Pepsi    Coke    Gatorade
------------------------------
Vanilla  Vanilla Lime
Cherry   Cherry  Fruit Punch
NULL     NULL    Grape

我尝试过FROM子句中的一系列外连接但是,我无法找到一种方法来生成结果而不显式调用列和/或表名。

select distinct t1.Pepsi, t2.Coke from 
(select 
    #test.Pepsi as Pepsi, 
    ROW_NUMBER() over (order by Pepsi) r 
 from #test
 where Pepsi is not null) as t1

full outer join

(select 
    #test.Coke as Coke, 
    ROW_NUMBER() over (order by Coke) r 
 from #test 
 where Coke is not null) as t2

on t1.r=t2.r 

原始表格如下:

Drink    Type     Price   Location  etc
Coke     Vanilla 
Coke     Cherry
Gatorade Lime
Gatorade Grape
.
.
.
Pepsi    Cherry

非常感谢任何建议或帮助。

1 个答案:

答案 0 :(得分:1)

DECLARE @t TABLE ([Drink] varchar(max), [Type] varchar(max), [Price] money )

INSERT @t
([Drink],[Type])
VALUES
('Coke','Vanilla'),
('Coke','Cherry'),
('Gatorade','Lime'),
('Gatorade','Grape'),
('Gatorade','Fruit Punch'),
('Pepsi','Vanilla'),
('Pepsi','Cherry')

;WITH t AS (
  SELECT
    [Drink],[Type],
    ROW_NUMBER() OVER(PARTITION BY [Drink] ORDER BY [Type] DESC) rn
  FROM @t
)
SELECT [Pepsi],[Coke],[Gatorade]
FROM t
PIVOT(MAX([Type]) FOR [Drink] IN ([Pepsi],[Coke],[Gatorade])) p