Link to home
Start Free TrialLog in
Avatar of TechNovation
TechNovationFlag for Netherlands

asked on

SQL Statement to move months from rows to columns?

Hi,

I have a source table structure like this:
Country      Month      Year       Amount
A-land        6              2005          100
B-Land       5              2005          110
B-Land       7              2005            90
C-Land       6              2005          200
C-Land       2              2005            70
D-Land       8              2005            30
...                .. .           .........             ..

And I would like to get a short report by country in row and months in column like:
Country     Jan    Fev    Mar     ...     Dec
A-Land       70      20       1      ...      13
B-Land       20      100     7      ...      17
C-Land       70      20      20      ...      18

For selected countries only (in this case A, B, and C)

What code should I use to move get it moving the month from rows to columns?

Avatar of momi_sabag
momi_sabag
Flag of United States of America image

select  country,
  sum (case when month = 1 then amount else 0 end) as Jan,
  sum (case when month = 2 then amount else 0 end) as Feb,
  ...
    sum (case when month = 12 then amount else 0 end) as Dec
from my_table
where country in ('A-Land','B-Land','C-Land')
Avatar of TechNovation

ASKER

is this also grouping per country?
Avatar of Zberteoc
You need the group by as well:
select  country,
  sum (case when month = 1 then amount else 0 end) as Jan,
  sum (case when month = 2 then amount else 0 end) as Feb,
  ...
    sum (case when month = 12 then amount else 0 end) as Dec
from my_table
where country in ('A-Land','B-Land','C-Land')
group by country

Open in new window

Sorry, it seems like they need the total number of invoices instead of the total amount of invoices. Would that mean a change to Count instead of Sum?:

count (case when month = 1 then amount else 0 end) as Jan,

Would it work?
why do you go for this, you can PIVOT.



SELECT * from (select country,[MONTH] ,amount FROM testing where country in ('A-land','B-Land','C-Land')) up
PIVOT (count(amount) for [month] in ([6], [7])) AS pivo
 
 
--i have used below table and data
create table testing
(
country varchar(10),
[Month] int,
[Year] int,
Amount int
)
 
insert into testing
select 'A-land',        6 ,             2005  ,        100 union all
select 'B-Land',       5  ,            2005  ,        110  union all
select 'B-Land',       7  ,            2005 ,           90  union all
select 'C-Land',      6   ,           2005  ,        200  union all
select 'C-Land',       2   ,           2005 ,           70  union all
select 'D-Land',       8    ,          2005 ,           30

Open in new window

above script was just demo, you can create dynamic pivot also for all months, have a look at my article at.

http://www.sqlhub.com/2009/03/dynamic-pivot-with-where-condition-in.html
here is completely dynamic count you want.



DECLARE @Cols NVARCHAR(2000)
SET @Cols=''
 
 
SELECT @Cols=@Cols+ '['+cast(s.[month] as varchar) +']'+ ', ' FROM
(SELECT DISTINCT [MONTH] FROM testing) AS s
 
SET @Cols=LEFT(@Cols,LEN(@Cols)-1)
 
 
SET @Cols='SELECT * from (select country,[MONTH] ,amount FROM testing) up
PIVOT (count(amount) for [month] in ('+@cols+')) AS pivo'
 
EXECUTE sp_executeSQL @Cols

Open in new window

SOLUTION
Avatar of RiteshShah
RiteshShah
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Zberteoc,

writing dynamic query is good rather than manually writing down all twelve month name, what if one need to include year name also like Jan-2005 etch. are you going to copy paste all column name for few years, lets say 5 years.

In dynamic query, you can change bit of code and you are done.
This is profoundly wrong and comes from little experience. The issue here is not to write less code because of laziness but to write the best code that performs the best according to the best practices.

Like I said, dynamic queries has it's own purpose and typing less is definitely not among them.

I recommend you to read more on this matter.
My only problem with this code:

  sum (case when Month = 1 then 1 else 0 end) as Jan,

is that I have to add to the group by statement the column [Month] and in that case I get for the same country as many rows as months (12 times) and each rows has the count of only the relevant month.

How do I get rid of the month in the group by statement, as SQL gets nervous and wants it there?
RiteshShah,
You query looks quite sofisticated and I would like to use it as well but I do not even know whether I need to replace some thing in it or just blindly copy paste and it would do all.

Guys, for me you're both experts, and both your methods will apparently work, and I do respect each of your approaches, I just want to get them running without mistakes:
1- normal query, I get 12 rows for each country because of the Month required in the group by statement
2- Dynamic query, I'm not familiar with and I just need to know how to make it work

Thanks to both
You don't need to ad the month column to the group by. That is the point of you question actually, turn the months from rows to columns so you need to use the query as I posted it with group by country only.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works great, may thanks
CGLuttrell's solution is actually the accepted one and that of Zberteoc is the assisted. Sorry I made a mistake.
Actually the solution was given by the first post by momi_sabag, I only added the group by while CGLuttrell didn't do annything else but replace 0 with NULL and SUM with COUNT, which is just a slightly different version for a solution that was already given. In my opinion he didn't add nothing really to the answer.

On the other hand the points went the way they were distributed regardless of which answer says Accepted or Assisted.should go to the f

On EE the accepted solution should be attributed to the first person that gives the correct and working answer. If someone comes later and just does cosmetic changes should not matter.