2

My database is structured like this:

Number | Month | Country
------------------------
63     | June  | Ireland
48     | June  | England
55     | June  | Spain
66     | May   | Ireland
33     | May   | England
53     | May   | Spain
44     | April | Ireland
44     | April | England
44     | April | Spain

I want to use an SQL statement to call this from the data above. Can anyone help me out please. Basically I want to split the number column into multiple other columns according to the month associated with it. I'm using sql-server 2000

Country | June | May | April
---------------------------
Ireland | 63   | 66  |  44
England | 48   | 33  |  44
Spain   | 55   | 53  |  44

2 Answers 2

8

That process is called pivoting. One way to do it:

 select  Country
 ,       sum(case when Month = 'June' then Number end) as June
 ,       sum(case when Month = 'May' then Number end) as May
 ,       sum(case when Month = 'April' then Number end) as April
 from    YourTable
 group by
         Country
3
  • Is it possible to do this if the number values are nvarchar instead of int values
    – kev670
    Jul 31, 2012 at 9:46
  • Sure, just cast them to int, like case when Month = 'April' then cast(Number as int) end
    – Andomar
    Aug 1, 2012 at 6:23
  • What if we have more than three month names in the main table? Aug 3, 2012 at 5:10
2

Try this,Here this query will give the proper results irrespective of the unique number of months.It means there is no need to hard code the months name as column names.

CREATE TABLE tbl1(Number int,Months varchar(10),Country varchar(10))
INSERT INTO tbl1
VALUES(63,'June','Ireland'),
(48,'June','England'),
(55,'June','Spain'),
(66,'May','Ireland'),
(33,'May','England'),
(53,'May','Spain'),
(44,'April','Ireland'),
(44,'April','England'),
(44,'April','Spain')

DECLARE @month_colms varchar(100)
DECLARE @sqlstr varchar(1000)
DECLARE @colname varchar(100)
select @month_colms=STUFF((select ', '+months from (select months from tbl1 group by months) a for xml path('')),1,1,'')
SET @sqlstr=''
While(CHARINDEX(',',@month_colms,1)>0)
BEGIN
SELECT @colname=LEFT(ltrim(rtrim(@month_colms)),CHARINDEX(',',ltrim(rtrim(@month_colms)),1)-1)
SET @month_colms=RIGHT(ltrim(rtrim(@month_colms)),LEN(ltrim(rtrim(@month_colms)))-CHARINDEX(',',ltrim(rtrim(@month_colms)),1))
SET @sqlstr=@sqlstr+','+'sum(case when Months = '''+@colname+''' then Number end) as '''+@colname+''''
END

SET @sqlstr=@sqlstr+','+'sum(case when Months = '''+ltrim(rtrim(@month_colms))+''' then Number end) as '''+@month_colms+''''

exec('select  Country'+@sqlstr+' from tbl1 group by Country')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.