Solved

SQL Statement to move months from rows to columns?

Posted on 2009-05-07
19
349 Views
Last Modified: 2012-05-06
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?

0
Comment
Question by:TechNovation
  • 7
  • 5
  • 5
  • +2
19 Comments
 
LVL 37

Expert Comment

by:momi_sabag
Comment Utility
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')
0
 

Author Comment

by:TechNovation
Comment Utility
is this also grouping per country?
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
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

0
 

Author Comment

by:TechNovation
Comment Utility
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?
0
 
LVL 31

Expert Comment

by:RiteshShah
Comment Utility
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

0
 
LVL 31

Expert Comment

by:RiteshShah
Comment Utility
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
0
 
LVL 31

Expert Comment

by:RiteshShah
Comment Utility
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

0
 
LVL 31

Assisted Solution

by:RiteshShah
RiteshShah earned 100 total points
Comment Utility
more precious, above script could just give you column with 1,2,3 as month header not Jan, feb etc. here is script which will give you month name as header.

DECLARE @Cols NVARCHAR(2000)

SET @Cols=''

 

 

SELECT @Cols=@Cols+ '['+DATENAME(month,convert(varchar,s.[month])+'-1-1900') +']'+ ', ' FROM

(SELECT DISTINCT [MONTH] FROM testing ) AS s order by s.[Month]
 
 

SET @Cols=LEFT(@Cols,LEN(@Cols)-1)

 

 

SET @Cols='SELECT * from (select country,DATENAME(month,convert(varchar,[month])+ ''-1-1900'') as [Month] ,amount FROM testing) up

PIVOT (count(amount) for [month] in ('+@cols+')) AS pivo'

 

 print @cols

EXECUTE sp_executeSQL @Cols

Open in new window

0
 
LVL 26

Accepted Solution

by:
Zberteoc earned 200 total points
Comment Utility
You definetely don't need and don't want either dynamic query for this. Dynamic queries are to be used for special cases when there is no other solution like when the name of a column or table changes for the same script. Other than that you are not supposed to use it as it doesn't give any advantage, just the opposite. Is a more for DBAs feature.

If you need the count then then you have to change the amount with 1 in the cases:
select  country,

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

  sum (case when month = 2 then 1 else 0 end) as Feb,

  ...

    sum (case when month = 12 then 1 else 0 end) as Dec

from my_table

where country in ('A-Land','B-Land','C-Land')

group by country

Open in new window

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 31

Expert Comment

by:RiteshShah
Comment Utility
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.
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
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.
0
 

Author Comment

by:TechNovation
Comment Utility
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?
0
 

Author Comment

by:TechNovation
Comment Utility
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.

0
 

Author Comment

by:TechNovation
Comment Utility
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
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
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.
0
 
LVL 26

Assisted Solution

by:Chris Luttrell
Chris Luttrell earned 200 total points
Comment Utility
Try this to get counts by countrh per month accross the columns.
select	country,

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

	count(case when month = 2 then 1 else null end) as Feb,

	count(case when month = 3 then 1 else null end) as Mar,

	count(case when month = 4 then 1 else null end) as Apr,

	count(case when month = 5 then 1 else null end) as May,

	count(case when month = 6 then 1 else null end) as Jun,

	count(case when month = 7 then 1 else null end) as Jul,

	count(case when month = 8 then 1 else null end) as Aug,

	count(case when month = 9 then 1 else null end) as Sep,

	count(case when month = 10 then 1 else null end) as Oct,

	count(case when month = 11 then 1 else null end) as Nov,

	count(case when month = 12 then 1 else null end) as Dec

from	yourTable

where country in ('A-Land','B-Land','C-Land')

group by 	country

Open in new window

0
 

Author Comment

by:TechNovation
Comment Utility
Works great, may thanks
0
 

Author Comment

by:TechNovation
Comment Utility
CGLuttrell's solution is actually the accepted one and that of Zberteoc is the assisted. Sorry I made a mistake.
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
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.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now