我有以下示例数据:
我正在使用此查询:
SELECT
SDC.[Date],
SDP.[Date] DateP,
[ManagerProductName],
SDC.[QuestionID],
SDC.QuestionValue [QuestionValueC],
SDP.QuestionValue [QuestionValueP]
FROM
[dbo].[SurveyData] SDC
INNER JOIN
[dbo].[SurveyData] SDP ON CAST(DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, SDC.Date), 0)) AS DATE) = SDP.date
AND SDC.QuestionID = SDP.QuestionID
AND SDC.SleeveID = SDP.SleeveID
INNER JOIN
[dbo].[FundManager] FM ON SDC.SleeveID = FM.SleeveID
INNER JOIN
[dbo].[Fund] F ON SDC.FundID = F.FundID
但是我需要将该数据转换为类似这样的内容:
答案 0 :(得分:0)
这就是answear:
SELECT
[Current Quarter]
,[Last Quarter]
,[FundName]
,[ManagerFullName]
,[ManagerProductName]
,[FileName], [1] [1 Current], [11] [1 Previous],[2], [12]
from
(
select
SDC.[Date] [Current Quarter]
,SDP.[Date] [Last Quarter]
,[FundName]
,[ManagerFullName]
,[ManagerProductName]
,SDC.[FileName], col, value
FROM [dbo].[SurveyData] SDC
INNER JOIN [dbo].[SurveyData] SDP
ON CAST(DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, SDC.Date), 0)) AS DATE) = SDP.date
AND SDC.QuestionID=SDP.QuestionID
AND SDC.SleeveID=SDP.SleeveID
INNER JOIN [dbo].[FundManager] FM
ON SDC.SleeveID=FM.SleeveID
INNER JOIN [dbo].[Fund] F
ON SDC.FundID=F.FundID
cross apply
(
select SDC.[QuestionValue], SDC.[QuestionID] union all -- AC 1/2
select SDP.[QuestionValue], SDC.[QuestionID] + 10 -- BD 11/12
) c (value, col)
) d
pivot
(
max(value)
for col in ([1], [2], [11], [12])
) piv;