我有以下结果集:
ID P1Score P2Score P3Score
===================================
22117617 NULL 50 NULL
22117617 1 NULL NULL
22117617 NULL NULL 40
我想要做的是,将这些行合并为一个。
我想将P1Score的值放在P1score列中,与P2score和P3score相同。
如何实现这一目标?
答案 0 :(得分:3)
select ID,
max(ISNULL(P1Score,0)),
max(ISNULL(P2Score,0)),
max(ISNULL(P3Score,0))
from [Score] group by ID
答案 1 :(得分:1)
你可以直接使用group by和sum()函数,因为如果你有单个Id的多个分数,那么sum就是合适的。
SELECT ID
,sum(P1Score) AS P1Score
,sum(P2Score) AS P2Score
,sum(P3Score) AS P3Score
FROM [Score]
GROUP BY ID
答案 2 :(得分:1)
如果您使用的是SQL Server 2012或更高版本,则可以使用MAX with OVER:
SELECT DISTINCT ID,
MAX(P1Score) OVER (ORDER BY ID) P1Score,
MAX(P2Score) OVER (ORDER BY ID) P2Score,
MAX(P3Score) OVER (ORDER BY ID) P3Score
FROM YourTable
输出:
ID P1Score P2Score P3Score
22117617 1 50 40
甚至转动:
SELECT *
FROM YourTable
UNPIVOT (
[Values] FOR PScores IN (P1Score, P2Score, P3Score)
) unp
PIVOT (
MAX([Values]) FOR PScores IN (P1Score, P2Score, P3Score)
) piv