• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 360
  • Last Modified:

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?

0
TechNovation
Asked:
TechNovation
  • 7
  • 5
  • 5
  • +2
3 Solutions
 
momi_sabagCommented:
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
 
TechNovationAuthor Commented:
is this also grouping per country?
0
 
ZberteocCommented:
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
Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
TechNovationAuthor Commented:
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
 
RiteshShahCommented:
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
 
RiteshShahCommented:
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
 
RiteshShahCommented:
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
 
RiteshShahCommented:
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
 
ZberteocCommented:
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
 
RiteshShahCommented:
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
 
ZberteocCommented:
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
 
TechNovationAuthor Commented:
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
 
TechNovationAuthor Commented:
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
 
TechNovationAuthor Commented:
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
 
ZberteocCommented:
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
 
Chris LuttrellSenior Database ArchitectCommented:
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
 
TechNovationAuthor Commented:
Works great, may thanks
0
 
TechNovationAuthor Commented:
CGLuttrell's solution is actually the accepted one and that of Zberteoc is the assisted. Sorry I made a mistake.
0
 
ZberteocCommented:
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

Get quick recovery of individual SharePoint items

Free tool – Veeam Explorer for Microsoft SharePoint, enables fast, easy restores of SharePoint sites, documents, libraries and lists — all with no agents to manage and no additional licenses to buy.

  • 7
  • 5
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now