Postgres选择昨天首次出现的记录

时间:2015-09-18 10:46:24

标签: sql postgresql greatest-n-per-group

我试图选择在最后一天中首次看到的所有记录以及其他一些聚合但我无法弄明白,因为在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;

我也有一个子查询的游戏,但没有让它工作。任何想法如何做到这一点?

1 个答案:

答案 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;