在子查询中包装数据透视转换并将其别名

时间:2017-10-23 19:36:25

标签: sql sql-server

我试图为客户创建一个解决方案,这需要我在SQL中执行行到列数据转换,然后通过子查询访问此数据。

我们有一个基于CTE的解决方案,我们认为可行,但是我们必须将此查询插入到shell查询中,以便将它与我们系统的UI一起使用,并且CTE解决方案不可行。

但是,我们知道如果我们可以通过应该工作的嵌套子查询访问数据透视转换数据。

下面是PIVOT转换的一个工作示例,并尝试使用我们希望可以在以后的连接中使用的子查询/别名解决方案的代码。

-- create the test data

create table #testData
(
    PK int, 
    DayID DateTime, 
    ReferenceCategorical VarChar(50),
    Value numeric
)

Insert Into #testData(PK, DayID, ReferenceCategorical, Value) VALUES (1,  
'2017-10-1', 'Red', 1516)
Insert Into #testData(PK, DayID, ReferenceCategorical, Value)VALUES (2,          
'2017-10-1', 'Blue', 1776)
Insert Into #testData(PK, DayID, ReferenceCategorical, Value)VALUES (3,      
'2017-10-1','Green', 1733)
Insert Into #testData(PK, DayID, ReferenceCategorical, Value)VALUES (4,  
'2017-10-2', 'Red', 1439)
Insert Into #testData(PK, DayID, ReferenceCategorical, Value)VALUES (5,  
'2017-10-2', 'Blue', 1882)
Insert Into #testData(PK, DayID, ReferenceCategorical, Value)VALUES (6,  
'2017-10-2', 'Green', 1372)

-- the rows to columns tranformation 

select DayID, [Red] ,[Blue], [Green]
FROM (select * from #testData) og       
PIVOT(  
max(Value)  
FOR  ReferenceCategorical in ([Red] ,[Blue], [Green] )
) pvt

这个尝试过的代码不起作用,但应该显示我们想要做的事情。

select * from 
( select DayID, [Red] ,[Blue], [Green]
FROM (select DayID, ReferenceCategorical, Value from #testData) og       
PIVOT(  
max(Value)  
FOR  ReferenceCategorical in ([Red] ,[Blue], [Green] )
) pvt)

2 个答案:

答案 0 :(得分:1)

只需要AS T

等别名
select * from 
( select DayID, [Red] ,[Blue], [Green]
FROM (select DayID, ReferenceCategorical, Value from #testData) og       
PIVOT(  
max(Value)  
FOR  ReferenceCategorical in ([Red] ,[Blue], [Green] )
) pvt) AS T

答案 1 :(得分:0)

I think you just need to alias the entire query. Here is an example showing how you would join the sub-query back to testData, for example:

SELECT DISTINCT #testData.dayID as main_query, sub.*
FROM #testData
INNER JOIN
(select DayID, [Red] ,[Blue], [Green]
FROM (select * from #testData) og       
PIVOT(  
max(Value)  
FOR  ReferenceCategorical in ([Red] ,[Blue], [Green] )
) pvt) sub
ON #testData.dayID = sub.dayID

Available here: http://rextester.com/RCW4104