Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a count MySQL query?

Tags:

sql

mysql

pivot

I have the following table:

UID | ID  | Type
1   | 1   | product
1   | 2   | product
1   | 3   | service
1   | 4   | product
1   | 5   | product
2   | 6   | service
1   | 7   | order
2   | 8   | invoice
2   | 9   | product

I want to end up with:

UID | product | service | invoice | order
1   |  4      |  1      |  0      |  1
2   |  1      |  1      |  1      |  0

What would the SQL query look like? Or at least, the most sufficient one?

like image 473
coderama Avatar asked Jun 04 '26 20:06

coderama


1 Answers

If you really only need those four types, then you can hard-code the values as follows:

select UID,
    count(case when type='product' then 1 else null end) as product,
    count(case when type='service' then 1 else null end) as service,
    count(case when type='invoice' then 1 else null end) as invoice,
    count(case when type='order' then 1 else null end) as order
from MyTable
group by UID
order by UID    
like image 172
D'Arcy Rittich Avatar answered Jun 07 '26 09:06

D'Arcy Rittich