duanpo1498 2011-10-24 15:43
浏览 100
已采纳

如何在一个表中显示多行,另一个表中的一行作为单行

I have two tables. Table "user" contains user_id, user_name Table "Transactions" contains user_id, transactions

Eg:

TABLE USER:
user_id, user_name
1, Ram
2, John
3, Rahim

TABLE Transactions
user_id, transactions
1,  500
1, 300
2, 250
1, 450
3, 100
1, 250
3, 50

I want to display the result as:

user_name, Total
Ram, 1500*
John, 250
Rahim, 150
  • it is the sum of all transactions of that particular user

How can I do this?

  • 写回答

3条回答 默认 最新

  • duangou1868 2011-10-24 15:46
    关注
    SELECT 
        u.user_name, 
        SUM(t.transactions) Total
    FROM users u
    LEFT JOIN transactions t ON t.user_id = u.user_id
    GROUP BY t.user_id
    

    I think you should use LEFT JOIN because it should select user's total (NULL) in any case, even if it's 0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog