SQL查找列的NULL和非NULL条目数

时间:2014-06-06 03:04:38

标签: sql

对于每个POSTAL_CODE,我想知道有多少NULL TIME_VISITED以及有多少NOT NULL TIME_VISITEDs

CREATE TABLE VISITS
(
 ID INTEGER NOT NULL,
 POSTAL_CODE VARCHAR(5) NOT NULL,
 TIME_VISITED TIMESTAMP,
 CONSTRAINT PK_VISITS PRIMARY KEY (ID)
);

示例数据:

INSERT INTO VISITS (ID, POSTAL_CODE, TIME_VISITED) VALUES ('234', '01910', '21.04.2014, 10:13:33.000');
INSERT INTO VISITS (ID, POSTAL_CODE, TIME_VISITED) VALUES ('334', '01910', '28.04.2014, 13:13:33.000');
INSERT INTO VISITS (ID, POSTAL_CODE, TIME_VISITED) VALUES ('433', '01910', '29.04.2014, 13:03:19.000');
INSERT INTO VISITS (ID, POSTAL_CODE, TIME_VISITED) VALUES ('533', '01910', NULL);
INSERT INTO VISITS (ID, POSTAL_CODE, TIME_VISITED) VALUES ('833', '01910', NULL);

这是我想要的上述数据的输出:

POSTAL_CODE = 01910,NUM_TIME_VISITED_NULL = 2,NUM_TIME_VISITED_NOT_NULL = 3

我正在使用以下SQL

SELECT distinct r.POSTAL_CODE, 
   (select count(*) from VISITS p where p.POSTAL_CODE=r.POSTAL_CODE and p.TIME_VISITED is null) as NUM_TIME_VISITED_NULL,
   (select count(*) from VISITS p where p.POSTAL_CODE=r.POSTAL_CODE and p.TIME_VISITED is not null) as NUM_TIME_VISITED_NOT_NULL
FROM VISITS r
ORDER BY r.POSTAL_CODE

如果表中有很多行

,查询需要很长时间

我需要做些哪些更改才能更快地获取此信息?

2 个答案:

答案 0 :(得分:3)

改为使用条件聚合:

select v.postal_code,
       sum(case when v.time_visited is null then 1 else 0
        end) as NumTimeVisitedNull,
       count(v.time_visited) as NumTimeVisitedNotNull
from visits v
group by v.postal_code;

注意:您也可以将其写为:

select v.postal_code,
       (count(*) - count(v.time_visited) ) as NumTimeVisitedNull,
       count(v.time_visited) as NumTimeVisitedNotNull
from visits v
group by v.postal_code;

count()函数专门计算非NULL值的数量。

答案 1 :(得分:1)

你可以一次完成这一切。 COUNT计算有多少非NULL。然后使用SUM语句的CASE来计算所有NULL。

SELECT POSTAL_CODE
      ,COUNT(TIME_VISITED) AS NUM_TIME_VISITED_NOT_NULL
      ,SUM(CASE WHEN TIME_VISITED IS NULL THEN 1 ELSE 0 END)) AS NUM_TIME_VISITED_NULL
FROM VISITS
GROUP BY POSTAL_CODE