简体   繁体   English

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

[英]How display multiple rows in a table with one row in another table as single row

I have two tables. 我有两张桌子。 Table "user" contains user_id, user_name Table "Transactions" contains user_id, transactions 表“user”包含user_id,user_name表“Transactions”包含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? 我怎样才能做到这一点?

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 我认为你应该使用LEFT JOIN,因为它应该在任何情况下选择用户的总数(NULL),即使它是0

SELECT u.user_id , SUM(t.transactions) AS total
FROM user AS u JOIN transactions AS t
GROUP BY u.user_id

Try 尝试

SELECT
    u.user_id,
    sum(t.transactions) as total
FROM
    user u
    JOIN transactions t ON u.user_id = t.user_id
GROUP BY
    u.user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MySQL查询-一个表中的单行,另一表中的多行 - MySQL query - single row in one table with multiple rows in another table 一个父行,另一个表中的多个子行。 如何将它们全部排成一排? - One parent row, multiple child rows in another table. How to get them all in one row? 将多行复制到另一张表中作为mysql中的单行 - Copying multiple rows into another table as a single row in mysql 将多行合并为表中的单行 - Combining multiple rows a single row in a table 如何在同一行中连接同一张表中的多行 - How to join multiple rows from same table in single row MYSQL单一查询可从一个表中检索单行,也可从另一表中检索多个行作为单个字段 - MYSQL Single query to retrieve both single row from one table and many rows as a single field from another 如何在单个html表行的musql表中显示多个行值 - How to display multiple row values in musql table in a single html table row 将具有多行的表联接到一行 - Join table with multiple rows to one row 加入1个表中具有单个ID /行但在另一个表中链接到多个行(相同ID)的SQL查询? - Join SQL query that has single id/row in 1 table, but links to multiple rows(same id) in another table? 将链接数据从一个表中的一行提取到另一表中的多行 - Extract linked data from one row in one table to multiple rows in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM