如何在Postgresql中的不同行中返回多个where子句?

6za6bjd0  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(98)

我有两个根据多个条件计算雇员总数的查询;唯一改变的是最后两个AND子句;我不知道如何在同一查询中返回结果。第一个查询

SELECT 
    COUNT(*)
FROM
(
SELECT
    E.NAME,
    E.LAST_NAME,
    E.BIRTH_DATE,
    E.ID
FROM
    EMPLOYEES E
WHERE E.BIRTH_DATE BETWEEN '2022-10-18 00:00:00' AND '2022-10-18 23:59:59'
AND E.NAME IS NOT NULL 
AND E.LAST_NAME IS NOT NULL
GROUP BY E.NAME, E.LAST_NAME, E.BIRTH_DATE,E.ID
) AUX;

第二个查询

SELECT 
    COUNT(*)
FROM
(
SELECT
    E.NAME,
    E.LAST_NAME,
    E.BIRTH_DATE,
    E.ID
FROM
    EMPLOYEES E
WHERE E.BIRTH_DATE BETWEEN '2022-10-18 00:00:00' AND '2022-10-18 23:59:59'
AND E.NAME IS NULL 
AND E.LAST_NAME IS NULL
GROUP BY E.NAME, E.LAST_NAME, E.BIRTH_DATE,E.ID
) AUX;

预期输出:
| 总计|
| - -|
| 3 --第一行|
| 5 --第二行|

2nbm6dog

2nbm6dog1#

最快的方法(即,最少的重写量)是简单的UNION您的查询一起这样:

select 'null names' as col1, count(*)
from employees e
where e.name is null
  and e.last_name is null
union
select 'not null', count(*)
from employees e
where e.name is not null
  and e.last_name is not null;

| 列1|计数(*)|
| - -|- -|
| 空名称|一个|
| 不为空|三个|
您还可以使用条件聚合,它使用较少的真实的空间并且非常易于阅读,并使用以下内容在列中生成输出......

select 
  sum(case when e.name is null and e.last_name is null then 1 else 0 end) as null_names, 
  sum(case when e.name is not null and e.last_name is not null then 1 else 0 end) as not_null
from employees e;

| 空名称|非空|
| - -|- -|
| 一个|三个|

np8igboo

np8igboo2#

SELECT count(*) filter (WHERE e.name IS NOT NULL AND e.last_name IS NOT NULL) as named
     , count(*) filter (WHERE e.name IS NULL AND e.last_name IS NULL) as unnamed
  FROM employees e
 WHERE e.birth_date BETWEEN '2022-10-18 00:00:00' AND '2022-10-18 23:59:59'
;

| 已命名|未命名的|
| - -|- -|
| 三个|五个|
与联合不同,这不需要两个单独的查询。只需要对结果集进行一次传递。
但你要求把结果分开列,所以......

SELECT unnest(ARRAY [
         count(*) filter (WHERE e.name IS NOT NULL AND e.last_name IS NOT NULL)
       , count(*) filter (WHERE e.name IS NULL AND e.last_name IS NULL)
       ])
  FROM employees e
 WHERE e.birth_date BETWEEN '2022-10-18 00:00:00' AND '2022-10-18 23:59:59'
;

| 拆巢|
| - -|
| 三个|
| 五个|
这会将两个结果放入一个数组中,然后将结果取消嵌套到单独的行中,同时仍保持相同的查询效率。

相关问题