0

我有一个表,我想在我的数据库中用作主表,每个季度都会更新数据。每个品牌每个季度都会更新他们的数据,其中包含新的信息行以及一列数据,这些数据将显示该数据所关注的季度和年份。所以数据集的一个例子是:

Brand | Share | Quarter | Year

Jonas |  2.4  |   4     |  2012

Smith |  3.6  |   4     |  2012

Dexes |  1.3  |   4     |  2012

Jonas |  3.0  |   1     |  2013

Smith |  1.1  |   1     |  2013

Dexes |  2.0  |   1     |  2013

Jonas |  1.1  |   2     |  2013

Smith |  4.0  |   2     |  2013

Dexes |  3.2  |   2     |  2013

我要创建的是一个查询,它将显示如下表:

Brand | Q4 12 | Q1 13 | Q2 13

Jonas | 2.4 | 3.0 | 1.1

Smith | 3.6 | 1.1 | 4.0

Dexes | 1.3 | 2.0 | 3.2

因此 Share 列使用季度和年份进行拆分。我可以创建一个基本的选择查询和连接表,但我不知道如何从在同一个表中拆分列开始。我会很感激任何帮助。

谢谢!

4

1 回答 1

0

在 T-SQL 中,您可以为此使用数据透视表运算符:

create table table1 (Brand varchar(20), Share decimal(10,2), [Quarter] int, [Year] int);

insert into table1 values 
('Jonas', 2.4, 4, 2012),
('Smith', 3.6, 4, 2012),
('Dexes', 1.3, 4, 2012),
('Jonas', 3.0, 1, 2013),
('Smith', 1.1, 1, 2013),
('Dexes', 2.0, 1, 2013),
('Jonas', 1.1, 2, 2013),
('Smith', 4.0, 2, 2013),
('Dexes', 3.2, 2, 2013)

select * 
from 
(select brand,Share,'Q' + cast([Quarter]as varchar(1)) +'-'+ cast([Year] as varchar(4)) as QuarterYear
from table1)D
Pivot (sum (share)
       for QuarterYear
       in ([Q4-2012],[Q1-2013],[Q2-2013]))T;

动态查询:

DECLARE @columns NVARCHAR(MAX)      
       ,@sql NVARCHAR(MAX);

SET @columns = N'';
--Get column names for entire pivoting
SELECT @columns += N', ' + QUOTENAME(QuarterYear)
  FROM (select distinct 'Q' + cast([Quarter]as varchar(1)) +'-'+ cast([Year] as varchar(4)) as QuarterYear 
        from table1
       ) AS T;  
PRINT @columns;

SET @sql = N' SELECT brand, ' + STUFF(@columns, 1, 2, '') + '
FROM
(select brand,Share,''Q'' + cast([Quarter]as varchar(1)) +''-''+ cast([Year] as varchar(4)) as QuarterYear
from table1 ) as D
PIVOT
(
  sum (share)
  for QuarterYear IN ('
  + STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '')
  + '))T
'

EXEC sp_executesql @sql;
于 2013-10-17T12:22:10.147 回答