在MySQL中选择2个相关表

时间:2017-11-14 15:32:44

标签: mysql

我有这两张桌子:

表用户:

id | name
---------
1  | Joe
2  | Sara
3  | Michael

表销售:

id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3

我想要以下内容:

User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0    

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

SELECT Users.name,
SUM(Case 
   WHEN product='Car' then 1
   ELSE 0
) AS Car,
SUM(Case 
   WHEN product='Truck' then 1
   ELSE 0
) AS Truck   ,
SUM(Case 
   WHEN product='Motorcycle' then 1
   ELSE 0
) AS Motorcycle,
FROM Users
LEFT JOIN Sales ON Users.id = Sales.user_id
GROUP BY Users.name

答案 1 :(得分:0)

SELECT
    name as UserName ,  
    SUM(product= 'Car')AS Car,
    SUM(product= 'Truck')AS Truck,
    SUM(product= 'motorcycle') AS motorcycle
FROM Users join Sales
on Users.id = Sales.user_id
GROUP BY name 

希望它有所帮助,但这仍然是一个标准解决方案,您应该检查数据透视表。

答案 2 :(得分:0)

- 对于少量产品,

Select username
, Sum(case when product = 'Car' then 1 else 0 End) Cars
, Sum(case when product = 'Truck' then 1 else 0 End) Truck
, Sum(case when product = 'motorcycle' then 1 else 0 End) motorcycle
From Sales s join users u on s.userid = u.userid
group by username