我在具有潜在NULL值的字段上使用ARRAY_AGG
,然后我想要稍后检查该数组是否为NULL。例如:
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
数组等于{,'成功'}。如何检查此数组是否为NULL值?
答案 0 :(得分: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
列中不存在的值,然后检查该“魔法”值。
答案 1 :(得分:0)
你可以尝试取消嵌套你的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)