首页 > 解决方案 > 如何在 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"
 }
}

这就像我需要做的

标签: mysqlsql

解决方案


试试这个:

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


推荐阅读