在使用 CASE 语句重写查询时需要帮助

Need help in rewriting the query using CASE statement

SELECT distinct 
    ID, 
    LOWER(IFF(REGEXP_COUNT(pos_id, '^[0-9]+$')= 1, NULL, pos_id)) as pos 
FROM table1
WHERE date='2022-02-02'
    AND pos_id is not null
    AND id='12345';

当我 运行 上述查询时,我得到的结果类似于

ID POS
12345 894f4bb2597f

但是当我 运行 下面我使用 CASE 的查询时,我得到 NULL 值和 NOT NULL 值。

SELECT distinct 
    ID, 
    CASE WHEN REGEXP_COUNT(pos_id, '^[0-9]+$')= 1 AND pos_id IS NOT NULL THEN NULL ELSE pos_id
    END as pos 
FROM table1
WHERE date='2022-02-02'
    AND pos_id is not null
    AND id='12345';
ID POS
12345 894f4bb2597f
12345 NULL

对于一个 ID,我得到的也是 NULL,而不是 NULL 值。

我需要删除 WHERE 子句中的 pos_id is not null 并将其添加到 CASE 语句中。

如何通过从 WHERE 子句中删除条件 - pos_id is not null 来使用 CASE 语句重写此查询?

我使用 CASE 语句尝试了以下查询,但没有得到正确的结果:

SELECT distinct 
    ID,
    CASE when REGEXP_COUNT(pos_id,'^[0-9]+$')=1 and 
       pos_id is not null  
                 THEN null else pos_id end
FROM table1
WHERE date='2022-02-02';     

当我使用 CASE 时,我得到的计数为 1,455,345 行 但是当我使用 - LOWER(IFF(REGEXP_COUNT(pos_id, '^[0-9]+$')= 1, NULL, pos_id 我得到 COUNT 为 2768 行

所以你问题的重点是最后一句:

When I use CASE, I'm getting the count as 1,455,345 ROWS but when I use - LOWER(IFF(REGEXP_COUNT(pos_id, '^[0-9]+$')= 1, NULL, pos_id I'm getting COUNT as 2768 rows

所以把你的 SQL 和一些试图理解“为什么结果不同”等的输入放在一起

你真的在问为什么我不降低那么我做的时候会有更多不同的值。

重点是区分大小写的计数将始终等于或大于不区分大小写的计数。

SELECT 
    column2 as pos_id,
    LOWER(IFF(REGEXP_COUNT(pos_id, '^[0-9]+$')= 1, NULL, pos_id)) as pos_i, 
    CASE 
        WHEN REGEXP_COUNT(pos_id, '^[0-9]+$') = 1 AND pos_id IS NOT NULL THEN NULL 
        ELSE pos_id
    END as pos_c
    ,lower(pos_c) as lower_pos_c
    ,count(distinct pos_i) over() as IFF_rows_count
    ,count(distinct pos_c) over() as CASE_rows_count
    ,count(distinct lower_pos_c) over() as LOWER_CASE_rows_count
FROM VALUES
    (12345, '894f4bb2597f'),
    (12346, '1234'),
    (12346, null),
    (123, 'aaa'),
    (123, 'Aaa'),
    (123, 'aAa'),
    (123, 'aaA');
POS_ID POS_I POS_C LOWER_POS_C IFF_ROWS_COUNT CASE_ROWS_COUNT LOWER_CASE_ROWS_COUNT
894f4bb2597f 894f4bb2597f 894f4bb2597f 894f4bb2597f 2 5 2
1234 null null null 2 5 2
null null null null 2 5 2
aaa aaa aaa aaa 2 5 2
Aaa aaa Aaa aaa 2 5 2
aAa aaa aAa aaa 2 5 2
aaA aaa aaA aaa 2 5 2