我认为我的问题很简单,答案也必须很简单。我只想在我的三栏文章之一中介绍一些关键点。 我有这样的查询:
SELECT AgentId, ReferenceTitle, PaymentValue FROM AgentPayments WHERE PaymentValue > 0
结果将是这样的:
AgentId ReferenceTitle PaymentValue
---------------------------------------------------
AgentId1 ReferenceTitle1 PayementValue1
AgentId1 ReferenceTitle2 PayementValue2
AgentId1 ReferenceTitle3 PayementValue3
AgentId2 ReferenceTitle2 PayementValue4
AgentId3 ReferenceTitle2 PayementValue5
AgentId3 ReferenceTitle3 PayementValue6
如您所见,它为我返回了一些记录,现在,我想以一种方式将结果转换为“ ReferenceTitle”列的每个值都变成自己的列,如下所示:
AgentId ReferenceTitle1 ReferenceTitle2 ReferenceTitle3
--------------------------------------------------------------------
AgentId1 PayementValue1 PayementValue2 PayementValue3
AgentId2 NULL PayementValue4 NULL
AgentId3 NULL PayementValue5 PayementValue6
我刚刚通过搜索发现了非常复杂的结果,但是我认为必须有一个简单的解决方案。 你觉得像我吗?
更新
我不知道“ ReferenceTitle”列的值,因此无法在查询中使用这些值。
答案 0 :(得分:1)
您可以使用条件聚合:
SELECT AgentId,
MAX(CASE WHEN ReferenceTitle='ReferenceTitle1' THEN PaymentValue END) AS ReferenceTitle1,
MAX(CASE WHEN ReferenceTitle='ReferenceTitle2' THEN PaymentValue END) AS ReferenceTitle2,
MAX(CASE WHEN ReferenceTitle='ReferenceTitle3' THEN PaymentValue END) AS ReferenceTitle3
FROM tab
GROUP BY AgentId;
答案 1 :(得分:0)
最后,我使用@lukasz Said这样的动态数据透视图获得了答案, 至少它不像我预期的那么复杂:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(ReferenceTitle)
FROM AgentPayments
WHERE PaymentValue > 0
GROUP BY ReferenceTitle
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT @query = '
SELECT * FROM
(
SELECT
AgentId, ReferenceTitle, PaymentValue
FROM AgentPayments
) X
PIVOT
(
MAX(PaymentValue)
for ReferenceTitle in ('+@cols+')
) P'
EXEC SP_EXECUTESQL @query