我试图选择在最后一天中首次看到的所有记录以及其他一些聚合但我无法弄明白,因为在where子句中不允许聚合。< / p>
这是我的尝试:
SELECT m.m_id,
m,
SUM(count) AS e_count,
COUNT(DISTINCT(c_code)) AS c_count
FROM e
LEFT JOIN m ON e.m_id = m.m_id
WHERE MIN(e_t::date) = current_date - INTERVAL '1' day
GROUP BY 1
ORDER BY 3 DESC;
我也有一个子查询的游戏,但没有让它工作。任何想法如何做到这一点?
答案 0 :(得分:0)
您只需将逻辑放在HAVING
子句中:
SELECT m.m_id, m, SUM(count) AS e_count,
COUNT(DISTINCT(c_code)) AS c_count
FROM e LEFT JOIN
m
ON e.m_id = m.m_id
GROUP BY 1
HAVING MIN(e_t::date) = current_date - INTERVAL '1' day
ORDER BY 3 DESC;
但是,您可能会发现在聚合之前过滤更有效。您可以使用WHERE
子句和NOT EXISTS
:
SELECT m.m_id, m, SUM(count) AS e_count,
COUNT(DISTINCT(c_code)) AS c_count
FROM e LEFT JOIN
m
ON e.m_id = m.m_id
WHERE NOT EXISTS (SELECT 1
FROM e e2
WHERE e2.m_id = e.m_id AND
e_t::date < current_date - INTERVAL '1' day
)
GROUP BY 1
ORDER BY 3 DESC;