?
Solved

SQL Statement to move months from rows to columns?

Posted on 2009-05-07
19
Medium Priority
?
356 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 5
  • +2
19 Comments
 
LVL 37

Expert Comment

by:momi_sabag
ID: 24329601
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
ID: 24329914
is this also grouping per country?
0
 
LVL 27

Expert Comment

by:Zberteoc
ID: 24332932
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
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 

Author Comment

by:TechNovation
ID: 24334233
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
ID: 24334872
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
ID: 24334885
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
ID: 24334920
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 400 total points
ID: 24335567
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 27

Accepted Solution

by:
Zberteoc earned 800 total points
ID: 24336047
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
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24336081
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 27

Expert Comment

by:Zberteoc
ID: 24336221
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
ID: 24336317
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
ID: 24336362
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
ID: 24336392
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 27

Expert Comment

by:Zberteoc
ID: 24337835
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 27

Assisted Solution

by:Chris Luttrell
Chris Luttrell earned 800 total points
ID: 24341552
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
ID: 24344580
Works great, may thanks
0
 

Author Comment

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

Expert Comment

by:Zberteoc
ID: 24345956
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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

771 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