K
K
Kolger2013-11-20 19:44:19
MySQL
Kolger, 2013-11-20 19:44:19

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

2 answer(s)
M
Mulder_ua, 2013-11-20
@Mulder_ua

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

W
Webdesus, 2013-11-20
@Webdesus

Here is the solution to your problem

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question