我有一个表,我想在我的数据库中用作主表,每个季度都会更新数据。每个季度,每个品牌都会更新新的信息行以及一列数据,这些数据将显示数据所查看的季度和年份。所以数据集的一个例子是:
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
因此,使用季度和年份拆分“共享”列以将其拆分。我可以创建一个基本的选择查询和连接表,但我不知道如何开始在同一个表中拆分列。我很感激任何帮助。
谢谢!
答案 0 :(得分: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;