答案 0 :(得分:1)
如果您有一个有限的静态测试列表,并且没有用户再进行一次测试,则可以这样做:
SELECT UserID,
SUM(Result * (Unit = "Test 1")) AS "Test 1",
SUM(Result * (Unit = "Test 2")) AS "Test 2",
SUM(Result * (Unit = "Test 3")) AS "Test 3"
FROM table
GROUP BY UserID;
这通过将GROUP上的SUM用作所有条目的加权总和来进行加权,所有条目的权重为1
(用于匹配测试的行),0
(对于所有其他行)(比较的结果为1表示TRUE,表示FALSE为0。
修改
正如@Nick在他的评论中指出的那样,您可以使用CASE而不是布尔乘以样式来采用更具可读性和较少依赖实现的方式:
SELECT UserID,
SUM(CASE WHEN Unit = "Test 1" THEN Result ELSE 0 END) AS "Test 1",
SUM(CASE WHEN Unit = "Test 2" THEN Result ELSE 0 END) AS "Test 2",
SUM(CASE WHEN Unit = "Test 3" THEN Result ELSE 0 END) AS "Test 3"
FROM table
GROUP BY UserID;