sql - 查询 : Show the name of the salesmen with more that 4 invoices in the same month

标签 sql database postgresql

PostgreSQL查询:显示当月有4张以上发票的业务员姓名。

表:文章、客户、发票、lines_invoice、省、镇、卖家

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

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

谢谢!

编辑:

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

codven = 代码销售商 nombre = 名字

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

最佳答案

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());

关于sql - 查询 : Show the name of the salesmen with more that 4 invoices in the same month,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670066/

相关文章:

database - Eclipse 的开源数据库插件?

c# - Visual Studio C# 和 SQL Server : connection property has not been initialized

database - 罗斯文的替代品

sql - 使用 GROUP BY 查询计算百分比

sql - 根据其他表中的匹配项选择分区

c# - 在一个数据访问层中处理多个连接字符串

c# - 一个连接中的多个 Insert 语句

sql - Postgresql 中 GROUP BY 的限制

mysql - 如何将一个表中超过 30 天记录的数据移动到另一个表中?

mysql - self 加入速度慢得令人痛苦