2016-10-20 39 views
0

我在具有潛在NULL值的字段上使用ARRAY_AGG,然後我想稍後檢查數組是否有空值。例如:ARRAY_AGG中的NULLS和檢查數組中的空值(Postgres 9.5.1)

WITH test AS 
(
SELECT 'A' AS call_id, NULL AS outcome 
UNION ALL 
SELECT 'A' AS call_id, 'success' AS outcome 
) 

SELECT * 
    FROM (
     SELECT call_id, ARRAY_AGG(outcome) AS outcome 
      FROM test 
      GROUP BY call_id 
     ) AS sub 
    WHERE outcome && ARRAY[NULL] 

但是這個查詢的結果是沒有行被返回。 ARRAY_AGG將創建一行,其中call_id ='A'和outcome數組等於{,'success'}。我如何檢查這個數組的NULL值?

+1

也許這將幫助:http://stackoverflow.com/questions/34848009/check-if-null-exists-in-postgres-array/34848472#34848472 – verhie

+0

這是有趣的,但' ...其中array_position(結果,null)不爲空應該工作。 – Abelisto

回答

0

除了寫一個函數,我不能想到會直接與數組做這件事。但是在聚合過程中如何計算NULL值呢?

WITH test (call_id, outcome) AS 
(
    values 
    ('A', null), 
    ('A', 'success'), 
    ('B', 'failure') 
) 
SELECT * 
FROM ( 
    SELECT call_id, 
     array_agg(outcome) AS outcome, 
     count(case when outcome is null then 1 end) as null_count 
    FROM test 
    GROUP BY call_id 
) AS sub 
where null_count > 0; 

您也可以使用having子句集成了直接進入select語句:

SELECT call_id, 
     array_agg(outcome) AS outcome 
FROM test 
GROUP BY call_id 
having count(case when outcome is null then 1 end) > 0 

另一種選擇是,以取代東西NULL值是不能在outcome列,然後檢查那個「魔術」值。

0

可能嘗試un-nesting你的outcome數組並檢查它是否存在空值。像這樣:

WITH test AS 
(
    SELECT 'A' AS call_id, null AS outcome 
    UNION ALL 
    SELECT 'A' AS call_id, 'success' AS outcome 
) 
SELECT * 
FROM (
    SELECT call_id, ARRAY_AGG(outcome) AS outcome 
    FROM test 
    GROUP BY call_id 
) AS sub 
WHERE EXISTS (select * from unnest(outcome) where unnest is null)