我的SQL的相关(大大缩写)部分:
Select
A.Client_ID,
,CASE
WHEN FN.FLD_CD = 1
THEN
FN.AMOUNT
ELSE
NULL
END AS "LN1"
,CASE
WHEN FN.FLD_CD = 2
THEN
FN.AMOUNT
ELSE
NULL
END AS "LN2"
,CASE
WHEN FN.FLD_CD = 3
THEN
FN.AMOUNT
ELSE
NULL
END AS "LN3"
(...and so on)
FROM
ASSESSMENT A,
FINANCE FN
WHERE
A.CLIENT_ID = FN.CLIENT_ID
AND FN.FLD_CD IN ( '1', '2', '3')
(other irrelevant stuff)
;
这将显示3个单独行上的查询结果(每个字段代码一行)。如何让它在一行显示全部?
例如,结果是:
Client_ID LN1 LN2 LN3
10001 20 - -
10001 - 30 -
10001 - - 40
但我希望这样:
Client ID LN1 LN2 LN3
10001 20 30 40
答案 0 :(得分:2)
使用条件聚合。假设每个客户端每个代码一个值:
SELECT A.Client_ID,
MAX(CASE WHEN FN.FLD_CD = 1 THEN FN.AMOUNT END) as LN1,
MAX(CASE WHEN FN.FLD_CD = 2 THEN FN.AMOUNT END) as LN2,
MAX(CASE WHEN FN.FLD_CD = 3 THEN FN.AMOUNT END) as LN3
FROM ASSESSMENT A JOIN
FINANCE FN
ON A.CLIENT_ID = FN.CLIENT_ID
WHERE FN.FLD_CD IN ('1', '2', '3')
(other irrelevant stuff)
GROUP BY A.CLIENT_ID;
注意:
FROM
子句中使用逗号。 始终使用明确的JOIN
语法。GROUP BY
子句以及SELECT
子句中的聚合函数。SUM()
而不是MAX()
。JOIN
(只需对f.CLIENT_ID
和SELECT
使用GROUP BY
。我假设JOIN
不在查询中的其他内容需要。