mysql - 如何在 SQL 中的三个或更多表之间进行 Group By
问题描述
我有第一个表名为 Header
id | user_id | created_on
------------------------
15 | 42 | 1 day ago
16 | 43 | 1 day ago
17 | 44 | 1 day ago
18 | 45 | 2 day ago
第二个表称为 Line
line_id | ph_name | quantity
----------------------------
15 | nokia | 3
16 | sumsung | 5
17 | nokia | 1
第三个表名为 User
id | name
--------------
42 | hi
43 | bye
44 | tata
那么如何根据用户数量并通过在SQL 查询或django 聚合 ORM中考虑今天的日期,将其关联和分组以给出如下所示的输出
{
{
"ph_name":"nokia",
"num_of_user":"2", //hi and tata are the users
"quantity":"4"
},
{
"ph_name":"samsung",
"num_of_user":"1", //bye is the only user
"quantity":"5"
}
}
解决方案
试试这个:
select ph_name, count(distinct first_table.user_id), sum(quantity)
from second_table
inner join (select * from first_table where created_on = '1 day ago') as first_table on second_table.line_id = first_table.id
inner join third_table on third_table.id = first_table.user_id
group by ph_name
注意,我不知道你的表是否在同一个数据库/模式中。您可能必须通过为表名添加前缀来指定数据库/模式schema/database_name.table_name
。
推荐阅读
- react-native - 尝试导入错误:“MaskedViewIOS”未从“react-native”导出
- python - 即使安装了 CUDAnn v10.1,Tensorflow 也没有在 GPU 上运行
- python - 如何在 python 中将二进制图像的内容/对象居中?
- hyperledger-fabric - 在 Hyperledger Fabric 中更新证书时会发生什么?
- amazon-web-services - 如何在 NodeJs 中发布自定义标头 AWS pinpoint 电子邮件
- c# - 连接到本地网络上的 MariaDB 服务器时出现命名管道提供程序错误
- javascript - 为什么我的循环没有在我的页面上显示我的 JSON/API 数据?
- javascript - vuejs中的所有部分切换问题
- asterisk - 无法使用星号服务器实时进行 SIP 呼叫
- swift - 带功能和按钮的工作表