向左联接3个表,并带有GROUP BY和SUM

时间:2018-09-19 16:42:38

标签: mysql left-join

我有3个表: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

==========

测试1:左联接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

==========

Test2:获取每个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”。谢谢。

3 个答案:

答案 0 :(得分:2)

我认为您可以尝试-

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您正在使用Oracle数据库,这将起作用:从TBLUSERS中选择t.UserID,t.UserName,tp.ProductKey,sum(tl.counter)合计t在t.userid = tp.userid上加入TBLPRODUCTS tp 将t.userid = tl.userid和tp.productkey = tl.productkey组的TBLDAILYLOG tl按tp.ProductKey,t.UserID,t.UserName的总数进行排序;