选择Id,其中列包含所有值

时间:2017-07-12 12:27:33

标签: sql group-by

请帮我一个SQL查询。这里是带有数据的测试表:

CREATE TABLE "Cats"
(
    "CatId" SERIAL PRIMARY KEY,
    "Name" character varying NOT NULL
);
CREATE TABLE "Measures"
(
    "MeasureId" SERIAL PRIMARY KEY,
    "CatId" integer NOT NULL REFERENCES "Cats",
    "Weight" double precision NOT NULL,
    "MeasureDay" integer NOT NULL
);

INSERT INTO "Cats" ("Name") VALUES 
    ('A'), ('B'), ('C')
;
INSERT INTO "Measures" ("CatId", "Weight", "MeasureDay") VALUES 
    (1, 5.0, 1),
    (1, 5.3, 2),
    (1, 6.1, 5),
    (2, 3.2, 1),
    (2, 3.5, 2),
    (2, 3.8, 3),
    (2, 4.0, 4),
    (2, 4.0, 5),
    (3, 6.6, 1),
    (3, 6.9, 2),
    (3, 7.0, 3),
    (3, 6.9, 4)
;

如何选择那些有5天测量值的CatId(MeasureDay获取(1,2,3,4,5)中的所有值)? 在此测试数据上,查询应返回2,因为只有CatId = 2的Cat具有所有日期(1,2,3,4,5)的度量值。

我假设我应该使用GROUP BY“CatId”和HAVING子句,但是HAVING中应该包含哪种查询?

2 个答案:

答案 0 :(得分:1)

使用group by

尝试这样做
select CatId 
from Measures
where MeasureDay in  (1, 2, 3, 4, 5)
group by CatId
having count(distinct MeasureDay) = 5;

答案 1 :(得分:0)

您可以使用聚合和having子句:

select m.CatId
from measures m
group by m.CatId
having count(distinct measureDay) = 5;