SELECT s.id, s.name
,date_trunc('month', i.sales_date::timestamp) AS month
,COUNT(i.id) AS invoices_for_month
FROM seller s
INNER JOIN invoices i ON (s.id = i.seller_id)
GROUP BY s.id, s.name, date_trunc('month', i.sales_date::timestamp)
HAVING COUNT(i.id) > 4
测试环境:
CREATE TABLE seller (id int, name text);
INSERT INTO seller VALUES(1, 'Joe');
INSERT INTO seller VALUES(2, 'Mike');
INSERT INTO seller VALUES(3, 'Tom');
CREATE TABLE invoices(id int, seller_id int, sales_date date);
INSERT INTO invoices VALUES(1, 1, now());
INSERT INTO invoices VALUES(2, 1, now() - interval '35' day);
INSERT INTO invoices VALUES(3, 1, now() - interval '37' day);
INSERT INTO invoices VALUES(4, 1, now() - interval '39' day);
INSERT INTO invoices VALUES(5, 1, now() - interval '40' day);
INSERT INTO invoices VALUES(6, 1, now() - interval '40' day);
INSERT INTO invoices VALUES(7, 2, now());