如何以下面的格式透视表并获取数据

时间:2015-12-16 02:57:51

标签: sql-server sql-server-2008-r2 pivot cross-join

目前,我有以下As-Is格式的数据 As-Is

并要求获得以下格式

ToBe

我正在使用SQL 2008 R2版本

我花了一些时间让这个工作使用Pivot \ Unpivot,但没有运气。如果有人可以帮助我解决这个神秘感,那就太棒了

2 个答案:

答案 0 :(得分:0)

declare @t table (RManager char(1),MeasureName varchar(10),Score float,Agg varchar(5),  [Rank] int)
insert into @t (RManager,MeasureName,Score,Agg,[Rank])
values('A', 'ATVScore', 0.03,   'WTD',  1),
('B',   'ATVScore', 0.05,   'WTD',  2),
('C',   'ATVScore', 0.12,   'WTD',  3),
('A',   'ATVScore', 34, 'MTD',  2),
('B','ABCScore',    12  ,'MTD', 3),
('C',   'ABCScore', 112,    'MTD',  1),
('A',   'ABCScore', 23, 'WTD',  3),
('B',   'ABCScore', 34, 'WTD',  2),
('C',   'ABCScore', 45, 'WTD',  1),
('A',   'ABCScore', 123 ,'MTD', 1),
('B',   'ABCScore', 34  ,'MTD', 3),
('C',   'ABCScore', 45  ,'MTD', 2)

数据

{{1}}

答案 1 :(得分:-1)

您可以进行条件聚合:

# get values of all unique cycle values
# returns an array containing: ["1234", "1235", ...]
values = db.coll2.distinct("cycles", {})

# find all documents where cycles value is in the values array 
# and update their status.
db.coll1.update({cycles: {$in: values}}, {$set: {status: "processed"}}, {multi: true})

如果SELECT RegionalManager, ATVScore = MAX(CASE WHEN MeasureName = 'ATVScore' THEN Score END), ABCScore = MAX(CASE WHEN MeasureName = 'ABCScore' THEN Score END), Agg, ATVRank = MAX(CASE WHEN MeasureName = 'ATVScore' THEN [Rank] END), ABCRank = MAX(CASE WHEN MeasureName = 'ABCScore' THEN [Rank] END) FROM tbl GROUP BY RegionalManager, Agg 的值不明,则需要动态执行:

MeasureName