Answer the question
In order to leave comments, you need to log in
Months in columns in a group by query in MySQL
Greetings!
Let's imagine an orders table that has:
date - order date
amount - order amount
source - order source
I would like to write a query that would return a table, where in the columns of the month, and in the rows - the amount of orders by source.
In this spirit: http://kolger.ru/monosnap/20131120aez6xe74hd.jpg
Surely there are ways to do this, but I did not find it by googling.
Answer the question
In order to leave comments, you need to log in
Hold on,
select source,
sum(case when datepart(mm, date) = 1 then amount else 0 end) as [January],
sum(case when datepart(mm, date) = 2 then amount else 0 end) as [.. .],
sum(case when datepart(mm, date) = 3 then amount else 0 end) aa [...],
sum(case when datepart(mm, date) = 4 then amount else 0 end) as [.. .],
sum(case when datepart(mm, date) = 5 then amount else 0 end) as [...],
sum(case when datepart(mm, date) = 6 then amount else 0 end) as [.. .],
sum(case when datepart(mm, date) = 7 then amount else 0 end) as [...],
sum(case when datepart(mm, date) = 8 then amount else 0 end) as [.. .],
sum(case when datepart(mm, date) = 9 then amount else 0 end) as [...],
sum(case when datepart(mm, date) = 10 then amount else 0 end) as [...],
sum(case when datepart(mm, date) = 11 then amount else 0 end) as [...],
sum(case when datepart(mm, date) = 12 then amount else 0 end) as [December]
group
by source
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question