How to group sums on weekdays in MySQL?

I have a table like this:

id | timestamp  | type  
-----------------------
1    2010-11-20   A
2    2010-11-20   A
3    2010-11-20   B
4    2010-11-21   A
5    2010-11-21   C
6    2010-11-27   B

and I need to count the strings for each type, grouped by weekday; eg:

weekday |  A  |  B  |  C 
--------------------------
5          2     2     0    -- the B column equals 2 because nov 20 and nov 27 are saturday
6          1     0     1

What would be the easiest solution for this?
I am not opposed to using views, variables, subqueries, etc.

+3
source share
1 answer

Using:

  SELECT WEEKDAY(t.timestamp) AS weekday,
         SUM(CASE WHEN t.type = 'A' THEN 1 ELSE 0 END) AS a,
         SUM(CASE WHEN t.type = 'B' THEN 1 ELSE 0 END) AS b,
         SUM(CASE WHEN t.type = 'C' THEN 1 ELSE 0 END) AS c
    FROM YOUR_TABLE t
GROUP BY WEEKDAY(t.timestamp)
+5
source

Source: https://habr.com/ru/post/1777516/


All Articles