count distinct包括null

时间:2013-02-23 21:10:03

标签: sql distinct

我有这个问题,我无法解决:

表格“habitacions”记录每个房间必须唤醒客人的时间(“hora”和“minut”栏)。如果时间是空值,则不得唤醒客人。给一个SQL句子返回不同小时数(忽略列“minut”),必须有人醒来。不愿意被唤醒被认为是一个新的不同时刻。

CREATE TABLE vigilants(
nom VARCHAR(20) PRIMARY key,
edat integer);

CREATE TABLE rondes(
hora INTEGER,
planta INTEGER,
vigilant VARCHAR(20) REFERENCES vigilants,
PRIMARY KEY(hora, planta));

CREATE TABLE habitacions(
num INTEGER,
planta INTEGER,
places INTEGER,
hora INTEGER,
minut INTEGER,
PRIMARY KEY(num, planta),
FOREIGN KEY(hora, planta) REFERENCES rondes);`

有这个限制:     尝试最小化解决查询所需的子查询数。此外,您不能使用以下结构:      - 在FROM或SELECT中选择。您可以拥有子查询(在WHERE或HAVING中选择SELECT)      - 聚合函数的组合,例如COUNT(COUNT ...)),SUM(COUNT ...))等。      - UNION,如果你能避免它。      - 非标准功能(如NVL)      - 案例

示例:使用此插入:

INSERT INTO vigilants(nom, edat) VALUES ('Mulder', 32);
INSERT INTO vigilants(nom, edat) VALUES ('Scully', 30);

INSERT INTO rondes(hora, planta, vigilant) VALUES (7, 1, 'Mulder');
INSERT INTO rondes(hora, planta, vigilant) VALUES (8, 1, 'Mulder');
INSERT INTO rondes(hora, planta, vigilant) VALUES (7, 2, 'Mulder');

INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (1, 1, 1, 7, 30);
INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (5, 1, 1, 7, 30);
INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (2, 1, 1, 8, 30);
INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (3, 1, 1, null, null);
INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (4, 1, 1, null, null);
INSERT INTO habitacions(num, planta, places, hora, minut) VALUES (1, 2, 1, null, null);

结果是3:)(7,8和null)

很多

1 个答案:

答案 0 :(得分:2)

提示:您可以将coalesce()功能与count(distinct)一起使用。

因此,允许以下内容:

select count(distinct coalesce(hour, -1))

它用-1替换NULL值,这不是有效值。这应该具有您正在寻找的效果。

相关问题