SQL Map列值到其他列

时间:2015-02-26 21:48:22

标签: sql sql-server-2012

我有一个透视查询,输出的内容如下:

[ID][Value][DateField1][Val1][Val2][Val3]
 1   R2     2014-01-01  0.3   3.2   3.1
 1   R1     2014-01-02  NULL  2.2   0.5
 1   R2     2014-01-02  0.7   NULL  NULL

我需要进一步修改它,以便将Value Column转换为:

[ID][DateField1][Val1][Val2][Val3][Val1R][Val2R][Val3R]
 1   2014-01-01  0.3   3.2   3.1   R2     R2     R2
 1   2014-01-02  0.7   2.2   0.5   R2     R1     R1

这不是一个支点,但我不完全确定如何去做。如果有人能指出我正确的方向,我真的很感激。谢谢!

2 个答案:

答案 0 :(得分:1)

也许您的查询过于复杂,所以我不确定使用with您可以使用它但我在下面的查询中进行了测试,这里the DEMO给出了您想要的内容:< / p>

create table query ([ID] int,
[Value] varchar(2),[DateField1] date,
[Val1] decimal(10,2),[Val2] decimal(10,2),
[Val3] decimal(10,2))

insert into query 
values(1,'R2','2014-01-01',0.3,3.2,3.1),
      (1,'R1','2014-01-02',null,2.2,0.5),
      (1,'R2','2014-01-02',0.7,null,null)

with cte
as
(
select * from query -- your query
)      
select distinct q.ID,q.DateField1,
   isnull(q.val1 ,(select top 1 qq.val1 from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val1 is not null)) val1,
   isnull(q.val2,(select top 1 qq.val2 from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val2 is not null)) val2,
   isnull(q.val3,(select top 1 qq.val3 from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val3 is not null))val3,
    case 
    when q.val1 is null then (select top 1 qq.value from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val1 is not null)
    else q.value end as val1R,
    case 
    when q.val2 is null then (select top 1 qq.value from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val2 is not null)
    else q.value end as val2R,
    case 
    when q.val3 is null then (select top 1 qq.value from cte qq 
                        where qq.ID=q.ID and qq.datefield1=q.datefield1
                        and qq.val3 is not null)
    else q.value end as val3R

 from cte q 

答案 1 :(得分:1)

with D as (
    yourquery
)
select
    ID, DateField1,
    sum(Val1) as Val1,
    sum(Val2) as Val2,
    sum(Val3) as Val3,
    min(case when Val1 is not null then Value end) as Val1R,
    min(case when Val2 is not null then Value end) as Val2R,
    min(case when Val3 is not null then Value end) as Val3R,
from D
group by ID, DateField1