Given table called events
with columns dt (timestamp)
and type (event type, example buy, sell, other)
I want to get all the events that happened in 2021
in Quarter
wise.
The result should hold 2 columns:
-
column1 = Quarter number followed by single quote and then last 2 digits of year.
example Q1’21, Q2’21, Q3’21, Q4’21 -
column2 = Format is ##=##, first ## indicates the type of event, and next # indicates total number of events of this particular type.
- Separate the types by semicolon and space.
- Sort this by descending order by total number of events and then the ascending order of type.
-
Sort the results in ascending order of column1.
I am able to write query to get individual columns, but when I combine them together I am getting errors with group columns.
Here is my query:
- To get column1:
select concat('Q', Quarter(dt), "'", RIGHT(YEAR(dt), 2)) as c1
from events
- To get column2:
select group_concat(concat(type, '=', cnt)) as c2
from (
select type, count(*) as cnt, quarter(dt) as qtr
from events where year(dt) = 2021
group by type, qtr
What is the correct way to solve this?
sample input:
2021-02-10 12:10:32 sell
2021-01-10 01:10:32 buy
2021-03-10 13:10:32 other
2021-11-10 13:10:32 buy
2021-12-10 13:10:32 sell
sample output:
Q1'21 buy=1; other=1; sell=1
Q4'21 buy=1; sell=1
2
Answers
Include the year in the subquery’s grouping.
Note that it’s not necessary to use
CONCAT()
insideGROUP_CONCAT()
, it automatically concatenates all the arguments.Data
use
subquery
,concat
,Group_concat
andright
as followsdbfiddle