【发布时间】:2018-03-11 21:54:26
【问题描述】:
我有两张桌子。一店“地点”:
TABLE location (
ID serial PRIMARY KEY,
name text NOT NULL,
description text NOT NULL
);
每个位置都有很多行“数据”:
TABLE data(
ID smallint REFERENCES location(ID),
date date,
rainfall int
);
我想查找所有具有跨越给定时间段的“数据”的位置,并且在该时间段内至少具有“最小”个值。我试过这个:
SELECT location.ID, location.name
FROM location
JOIN data
ON data.id = location.id
GROUP BY location.id
HAVING MIN(data.date) <= '$start_date'
AND
MAX(data.date) >= '$end_date'
AND
(SELECT COUNT(*) FROM data WHERE data.date >= '$start_date' AND data.date <= '$end_date') >= '$min'
ORDER BY location.ID
如果我取出倒数第二行(SELECT COUNT 行),它会正确返回具有跨越所需时间段的数据的位置(但不存在所需时间段内值的数量大于或等于的约束)到“分钟”)。
谁能告诉我如何施加约束? IE。我的“SELECT COUNT 行”出了什么问题。
以下示例数据可能有助于澄清我的问题:
示例数据:
location:
ID = 1, name = "London", description = "test location 1"
ID = 2, name = "New York", description = "test location 2"
数据:
ID = 1, date = 2001-01-01, rainfall = 0.0
ID = 1, date = 2001-01-02, rainfall = 0.0
ID = 1, date = 2001-01-03, rainfall = 0.0
ID = 1, date = 2001-01-04, rainfall = 0.0
ID = 1, date = 2001-01-05, rainfall = 0.0
ID = 1, date = 2001-01-06, rainfall = 0.0
ID = 1, date = 2001-01-07, rainfall = 0.0
ID = 2, date = 2001-01-01, rainfall = 0.0
ID = 2, date = 2001-01-04, rainfall = 0.0
ID = 2, date = 2001-01-05, rainfall = 0.0
ID = 2, date = 2017-01-01, rainfall = 0.0 # Not within the desired period, so is excluded
ID = 2, date = 2017-01-02, rainfall = 0.0 # Not within the desired period, so is excluded
ID = 2, date = 2017-01-03, rainfall = 0.0 # Not within the desired period, so is excluded
ID = 2, date = 2017-01-04, rainfall = 0.0 # Not within the desired period, so is excluded
如果我搜索数据介于 2001-01-01 和 2001-01-07 之间的所有位置,并且至少有 6 个数据值,它应该只返回位置 1 (ID=1)。不应返回第二个位置 (ID=2),因为它在所需时间段内没有所需数量的值。
【问题讨论】:
-
这个问题在我看来已经够清楚了。
标签: sql postgresql select