Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate log-table without using two selects

Tags:

select

mysql

Is there a way to form a query that would take this:

Id | action | object 
-------------
1 | view | article1 
2 | view | article2 
3 | view | article1 
4 | order | article1 
5 | order | article1 
6 | order | article3 

and produce this:

name     | views | orders
----------------------
article1 |   2   |   2
article2 |   1   |   0
article3 |   0   |   1

One solution would be using two selects and join them afterwards in the code. Is there a better one?

regards && tia

noircc

like image 656
noircc Avatar asked Jun 18 '26 01:06

noircc


1 Answers

Maybe something like this:

SELECT
    SUM(CASE WHEN Table1.action='view' THEN 1 ELSE 0 END) AS views,
    SUM(CASE WHEN Table1.action='order' THEN 1 ELSE 0 END) AS orders,
    Table1.object 
FROM
    Table1
GROUP BY
    Table1.object 
like image 182
Arion Avatar answered Jun 19 '26 15:06

Arion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!