我有一个带有以下结构和数据的SQL查询结果
ProductId #date #customercode # SomeIndex # SomeIndexvalue
13 2011-10-01 1 A1 9397062
14 2011-10-01 2 A1 3575045
15 2011-10-01 3 A1 3575321
13 2011-10-01 1 A2 1318774
14 2011-10-01 2 A2 838924
15 2011-10-01 3 A2 8942430
在此索引值中,productid,date,customercode是唯一的。现在我需要将SomeIndex设为列,以便在给定数据中只有三行。即,以下结构
ProductId #date #customercode # A1 # A2
13 2011-10-01 1 9397062 1318774
14 2011-10-01 2 3575045 838924
15 2011-10-01 3 3575321 8942430
我正在使用sqlserver 2008.任何人都可以帮助我。在此先感谢大家
答案 0 :(得分:1)
SELECT ProductId, [#date], [#customercode],
MIN(CASE WHEN [#SomeIndex] = 'A1' THEN [#SomeIndexvalue] END) [#A1],
MIN(CASE WHEN [#SomeIndex] = 'A2' THEN [#SomeIndexvalue] END) [#A2]
FROM YourTable
GROUP BY ProductId, [#date], [#customercode]
答案 1 :(得分:1)
使用PIVOT运算符(SQL 2008版本)
create table #test(
ProductId int,
dt date,
customercode int,
someindex varchar(255),
SomeIndexvalue int
)
insert into #test values
(13,'2011-10-01',1,'A1',9397062),
(14,'2011-10-01',2,'A1',3575045),
(15,'2011-10-01',3,'A1',3575321),
(13,'2011-10-01',1,'A2',1318774),
(14,'2011-10-01',2,'A2',838924),
(15,'2011-10-01',3,'A2',8942430)
select * from
(
select
*
from
#test
)DATA_TO_PIVOT
PIVOT
(
MAX(SomeIndexvalue) for someindex in ([A1],[A2])
)PIVOTED_DATA