oracle 当计数超过一个时,在SQL中放置静态值,否则保留原始值

1bqhqjot  于 2023-01-08  发布在  Oracle
关注(0)|答案(1)|浏览(98)

当一列有多个值时,我希望显示静态值'More than one Value',否则我希望保留原始列值。
这样就得到了我想要的结果,但结果仅限于HAVING COUNT(B.COL3) > 1条件:

SELECT
    A.COL1,
    A.COL2,
    'More than one Value' AS COL3
FROM TBL1 A
RIGHT JOIN TBL2 B ON A.TBL1-ID = B.TBL2-ID
GROUP BY A.COL1, A.COL2
HAVING COUNT(B.COL3) > 1;

这个失败了

SELECT
    A.COL1,
    A.COL2,
    CASE WHEN COUNT (B.COL3) >1 THEN 'More than one Value' ELSE B.COL3 END AS COL3
FROM TBL1 A
RIGHT OUTER JOIN TBL2 B ON A.TBL1-ID = B.TBL2-ID
GROUP BY A.COL1, A.COL2;

下面是数据的模型
| COL1| COL2| COL3|
| - ------|- ------|- ------|
| A类|B| C级|
| A1|地下一层|多个值|

ogq8wdun

ogq8wdun1#

假设B.COL3是字符串,则:

SELECT A.COL1,
       A.COL2,
       CASE
       WHEN COUNT(B.COL3) > 1
       THEN 'More than one Value'
       ELSE MAX(B.COL3)
       END AS COL3
FROM   TBL1 A
       RIGHT JOIN TBL2 B
       ON A.TBL1_ID = B.TBL2_ID
GROUP BY A.COL1, A.COL2;

如果不是字符串,则使用TO_CHAR(MAX(B.col3))
其中,对于示例数据:

CREATE TABLE tbl1 (col1, col2, tbl1_id) AS
SELECT 'A',  'B',  1 FROM DUAL UNION ALL
SELECT 'A1', 'B1', 2 FROM DUAL;

CREATE TABLE tbl2 (col3, tbl2_id) AS
SELECT 'C',  1 FROM DUAL UNION ALL
SELECT 'C1', 2 FROM DUAL UNION ALL
SELECT 'C2', 2 FROM DUAL;

输出:
| COL1| COL2| COL3|
| - ------|- ------|- ------|
| A类|B| C级|
| A1|地下一层|多个值|
fiddle

相关问题