0

PostgreSQL查询:显示当月发票超过4张的业务员姓名。

表:articles, customers, invoices, lines_invoice, province, towns, sellers

我的查询返回值而不考虑同一个月的计数,我该怎么做?

select s.codseller, s.name 
from sellers s 
join invoices i using (codseller) 
group by s.codseller 
having count (codinvoice) > 4;

谢谢!

编辑:

屏幕上显示的正确解决方案是: 结果

codven = codseller nombre = 名称

在我的查询中,它显示了两行额外的行,因为它计算了具有超过 4 张发票但在不同月份的销售人员。

4

2 回答 2

2
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());
于 2012-05-20T01:36:31.970 回答
1

我会在这里留下答案,但格伦的答案更好

您必须在 group_by 子句中提取月份(未经测试):

select s.codseller, 
EXTRACT(MONTH FROM i.date) as month, 
EXTRACT(YEAR FROM i.date) as year, s.name 
from sellers s 
join invoices i using (codseller) 
group by s.codseller, month, year
having count (codinvoice) > 4;

另请查看只有日期时间字段时如何按月和年分组?

您还应该看看 postgresqls日期时间函数

于 2012-05-20T01:34:33.377 回答