2

我的数据库结构如下:

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

我想使用 SQL 语句从上面的数据中调用它。谁能帮帮我。基本上我想根据与之关联的月份将数字列拆分为多个其他列。我正在使用 sql-server 2000

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

2 回答 2

6

该过程称为旋转。一种方法:

 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
于 2012-07-30T15:53:30.907 回答
2

试试这个,这里这个查询将给出正确的结果,而不管月数是多少。这意味着不需要将月份名称硬编码为列名。

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')
于 2012-07-30T16:32:06.023 回答