[英]Select Data From 3 Different Tables Group By and Limit upto 3
I have 3 tables named as Referrals, Providers, Suppliers.我有 3 个表,分别命名为 Referrals、Providers、Suppliers。
Suppliers table供应商表
| id | name
| 1 | Supplier A
| 2 | Supplier B
| 3 | Supplier C
| 4 | Supplier D
Providers table提供者表
| id | name
| 1 | Provider A
| 2 | Provider B
| 3 | Provider C
| 4 | Provider D
Referrals table推荐表
| id | client_name | provider_id | supplier_id | created_at
| 1 | Client A | 1 | 1 | 2021-01-20
| 2 | Client B | 1 | 1 | 2021-01-21
| 1 | Client C | 2 | 1 | 2021-01-22
| 1 | Client A | 2 | 2 | 2021-01-23
| 1 | Client A | 3 | 2 | 2021-01-24
| 1 | Client A | 1 | 3 | 2021-01-24
| 1 | Client A | 4 | 3 | 2021-01-25
| 1 | Client A | 4 | 4 | 2021-01-26
| 1 | Client A | 1 | 1 | 2021-01-20
I want to count the number of referrals by each provider by supplier (top 3) in a month this format below:我想按以下格式计算每个供应商在一个月内按供应商(前 3 名)推荐的数量:
Result format should be:结果格式应为:
| id | referral_count | provider_id | supplier_id | created_at
| 1 | 3 | 1 | 1 | January
| 2 | 2 | 1 | 1 | January
| 1 | 1 | 2 | 1 | January
| 1 | 2 | 2 | 2 | January
| 1 | 3 | 3 | 2 | January
| 1 | 1 | 1 | 2 | January
| 1 | 2 | 4 | 3 | January
| 1 | 3 | 4 | 3 | January
| 1 | 4 | 1 | 3 | January
Thanks谢谢
If I understand correctly, you simply want a count()
as a window function:如果我理解正确,您只需要将count()
作为 window function:
select r.*,
count(*) over (partition by provider_id, supplier_id, year(created_at), month(created_at)) as referral_count
from referrals r;
You can use count(*)
window function to achieve that if your mysql version is 8 or higher:如果您的 mysql 版本为 8 或更高,您可以使用count(*)
window function 来实现:
select
id,
(count(client_name) over (partition by provider_id, supplier_id, year(created_at), monthname(created_at))) referral_count,
provider_id, supplier_id, monthname(created_at) created_at
from Referrals;
If you are using older version of MySQL then you can use below option with subquery:如果您使用的是旧版本的 MySQL 那么您可以将以下选项与子查询一起使用:
select id ,
(select count(*) from Referrals rf where rf.provider_id=r.Provider_id and rf.supplier_id=r.supplier_id
group by provider_id , supplier_id ,year(created_at),monthname(created_at)) referral_count,provider_id , supplier_id ,monthname( created_at) created_at
from Referrals r;
Output: Output:
id ID | provider_id provider_id | supplier_id供应商 ID | referral_count推荐数 | created_at created_at |
---|---|---|---|---|
1 1 | 1 1 | 1 1 | 3 3 | January一月 |
2 2 | 1 1 | 1 1 | 3 3 | January一月 |
1 1 | 2 2 | 1 1 | 1 1 | January一月 |
1 1 | 2 2 | 2 2 | 1 1 | January一月 |
1 1 | 3 3 | 2 2 | 1 1 | January一月 |
1 1 | 1 1 | 3 3 | 1 1 | January一月 |
1 1 | 4 4 | 3 3 | 1 1 | January一月 |
1 1 | 4 4 | 4 4 | 1 1 | January一月 |
1 1 | 1 1 | 1 1 | 3 3 | January一月 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.