0

I have these 2 tables:

Table Users:

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

Table Sales:

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

I want the following:

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

Any help would be appreciated

Sairam Santana
  • 63
  • 1
  • 1
  • 7

3 Answers3

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
Daniel E.
  • 2,440
  • 1
  • 14
  • 24
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 

hope it helps but still this is a standard solution you should check pivot Tables.

yazan
  • 518
  • 3
  • 16
0

--For a small number of products this works,

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 
Rob Presto
  • 16
  • 3