我正在尝试编写一个子查询来计算“TRACE_NO”的数量,如果只有一个实例,我希望它显示原始字符串。但是,如果它有多个'TRACE_NO'实例,我希望该行显示'Duplicate'。我究竟做错了什么?
SELECT
SL.FILE_NO AS FILE,
(SELECT CASE(WHEN TR.TRACE_NO HAVING COUNT(*) >1 THEN 'DUPLICATE' ELSE
TR.TRACE_NO)
FROM IASDB.TRACE_DETAIL TR
WHERE SL.INVOICE_NO = TR.INVOICE_NO
AND TR.TRACE_TYPE IN 'XX') AS XX
表
FILE XX
1120 | SEA
1315 | SDF
1251 | SEA
1251 | GEG
1991 | ATL
1235 | BOI
1235 | CVG
期望的输出:
FILE | XX
1120 | SEA
1315 | SDF
1251 | DUPLICATE
1991 | ATL
1235 | DUPLICATE
答案 0 :(得分:1)
假设这是更大查询的一部分,这可能是您想要的逻辑:
SELECT SL.FILE_NO AS FILE,
(SELECT CASE WHEN COUNT(*) > 1 THEN 'DUPLICATE' ELSE MIN(TR.TRACE_NO) END
FROM IASDB.TRACE_DETAIL TR
WHERE SL.INVOICE_NO = TR.INVOICE_NO AND TR.TRACE_TYPE IN 'XX'
) AS XX