从 GROUP BY 中获取包含 NULL 列的行

Get the row with a NULL column from GROUP BY

如何从下面的查询中获取 address_1 中具有 null 值的行。

SELECT id, address_1, address_2, address_3 FROM table GROUP BY address_2, address_3 HAVING COUNT(id) > 1;

所有分组中address_1中只有一行的值是null

id    address_1    address_2    address_3
-----------------------------------
1    7 Orange     High County  CA 10020
2                 High County  CA 10020
3    20 Orange    High County  CA 10020
4                 True Avenue  VA 24019
5    100 Apple    True Avenue  VA 24019
6    123 Apple    True Avenue  VA 24019
7                 Long Island  NY 10000
...

我想获取第 2 行和第 4 行的 ID(以相应地更新或删除它)。

SELECT id, address_1, address_2, address_3 
FROM table 
WHERE address_1 IS NULL 
group by address_2,address_3;

如果每组address_1中只有一行为空值则无需分组

这是你需要的吗?还是我没听懂?

要找到这样的 id 值,您可以使用:

SELECT id
FROM yourTable t1
WHERE address_1 IS NULL AND
      EXISTS (SELECT 1 FROM yourTable t2
              WHERE t2.address_2 = t1.address_2 AND
                    t2.address_3 = t1.address_3 AND
                    t2.id <> t1.id AND
                    t2.id IS NOT NULL);

Demo

对于此示例数据,您可以使用条件聚合:

SELECT MAX(CASE WHEN address_1 IS NULL THEN id END) id
FROM tablename
GROUP BY address_2, address_3
HAVING COUNT(address_1) > 0 AND COUNT(address_1) < COUNT(*);

参见demo