用groupby和sum左连接3个表

nnvyjq4y  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(375)

我有三张table:tblusers、tblproducts和tbldailylog:
tblusers公司

UserID  UserName
------  --------
  1001  Mary
  1002  John

TBL产品

UserID  ProductKey  ProductName
------  ----------  ----------  
  1001  key1        p1
  1001  key2        p2

tbldailylog公司

UserID  ProductKey  Counter  Updated
------  ----------  -------  ----------
  1001  key1             10  2018-01-01
  1001  key1             15  2018-01-02
  1001  key2             50  2018-01-01

==========
test1:left join 2表:tblusers和tblproducts
查询: SELECT tblusers.UserID, tblusers.UserName, tblproducts.ProductKey FROM tblusers LEFT JOIN tblproducts ON tblusers.UserID = tblproducts.UserID GROUP BY tblusers.UserID 结果:

UserID  UserName  ProductKey
------  --------  ----------
  1001  Mary      key1
  1001  Mary      key2
  1002  John

==========
测试2:获取每个productkey的总计数器
查询: SELECT UserID, ProductKey, SUM(Counter) as Total FROM tbldailylog GROUP BY ProductKey 结果:

UserID  ProductKey  Total
------  ----------  -----
  1001  key1           25
  1001  key2           50

==========
我想有下面的最终结果,我如何结合在一起的3个表?最终结果是按sum(counter)desc排序的。很抱歉,无法以良好的格式显示表数据以便于查看。谢谢你的帮助。
最终结果:

UserID  UserName  ProductKey  Total  ProductName
------  --------  ----------  -----  ----------
  1001  Mary      key2           50  p2
  1001  Mary      key1           25  p1
  1002  John

编辑:抱歉没有在我原来的帖子里说清楚。我在“tblproducts”和最终结果中添加了“productname”列,因此我们必须使用查询中的所有3个表,因为“tblusers”和“tbldailylog”中不存在“productname”。谢谢。

7jmck4yq

7jmck4yq1#

如果您使用的是oracle数据库,这将起作用:选择t.userid,t.username,tp.productkey,sum(tl.counter)total from tblusers t left join tblproducts tp on t.userid=tp.userid left join tbldailylog tl on t.userid=tl.userid和tp.productkey=tl.productkey group by tp.productkey,t.userid,t.username order by total;

r8uurelv

r8uurelv2#

我想你可以试试这个-

select tu.userid,
       tu.UserName,
       tdl.ProductKey,
       tp.ProductName,
       sum(tdl.Counter) as Total
  from tblusers tu
  left join tbldailylog tdl
    on tu.userid = tdl.userid
  left join tblproducts tp
    on tu.userid = tp.userid
 group by tu.userid, tu.UserName, tdl.ProductKey, tp.ProductName
 order by sum(tdl.counter) desc
i2loujxw

i2loujxw3#

SELECT l.UserID, u.UserName, l.ProductKey, p.ProductName SUM(l.Counter) as Total 
FROM tblUsers u
LEFT JOIN tbldailylog l ON l.UserID = u.UserID
LEFT JOIN tblProducts p ON p.UserID = t.UserID AND p.ProductKey = t.ProductKey
GROUP BY l.UserID, l.ProductKey, u.UserName, p.ProductName

相关问题