简体   繁体   English

MySQL select 总计在一个不同的查询中

[英]MySQL select total in a distinct query

I would like to get a total number of transactions per customer (company).我想获得每个客户(公司)的交易总数。 How can I add to this query a counter to calculate the number of records in the transaction table per Company?如何在此查询中添加一个计数器来计算每个公司的事务表中的记录数?

select DISTINCT c.CompanyName, c.ContactEmail
From Transactions tr
JOIN Tenants t on tr.tenantid = t.tenantid
JOIN Properties p on t.propertyid = p.propertyid
JOIN Company c on c.companyid = p.companyid

Thanks谢谢

Use GROUP BY :使用GROUP BY

SELECT c.CompanyName, c.ContactEmail, COUNT(*)
FROM Transactions tr JOIN
     Tenants t ON tr.tenantid = t.tenantid
     Properties p ON t.propertyid = p.propertyid
     Company c ON c.companyid = p.companyid
GROUP BY c.CompanyName, c.ContactEmail;
SELECT DISTINCT c.CompanyName, c.ContactEmail, COUNT(tr.id) total_tranactions From Transactions tr JOIN Tenants t on tr.tenantid = t.tenantid JOIN Properties p on t.propertyid = p.propertyid JOIN Company c on c.companyid = p.companyid GROUP BY c.CompanyName, c.ContactEmail;

user primary key of your transaction table in count COUNT() aggregate function.您的事务表的用户主键计数 COUNT() 聚合 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM