[英]SQL Server convert a table column values to names and assign 0 to the new columns if no value for a column
I would like to transform a table from rows to columns in SQL Server. 我想在SQL Server中将表从行转换为列。
Given table1: 给定表1:
id value1 value2
1 name1 9
1 name1 26
1 name1 15
2 name2 20
2 name2 18
2 name2 61
I need a table like: 我需要一个像这样的表:
id name1 name2
1 9 0
1 26 0
1 15 0
2 0 20
2 0 18
2 0 61
Can pivot help here? 可以在这里提供帮助吗? An efficient way is preferred to do the convert because the table is large.
由于表很大,因此首选进行转换的有效方法。
I have tried: 我努力了:
select
id, name1, name2
from
(select
id, value1, value2
from table1) d
pivot
(
max(value2)
for value1 in (name1, name2)
) piv;
But, it cannot provide all rows for same ID to combine with 0s. 但是,它不能为同一ID提供所有行以与0组合。
Thanks 谢谢
The 'secret' is to add a column to give uniqueness to each row within your 'nameX' groups. “秘密”是添加一列,以使“ nameX”组中的每一行具有唯一性。 I've used
ROW_NUMBER
. 我用过
ROW_NUMBER
。 Although PIVOT
requires an aggregate, with our 'faked uniqueness' MAX, MIN etc will suffice. 尽管
PIVOT
需要汇总,但使用我们的“伪造的唯一性”,MAX,MIN等就足够了。 The final piece is to replace any NULL
s with 0 in the outer select. 最后一步是在外部select中将任何
NULL
替换为0。
(BTW, we're on 2014 so I can't test this on 2008 - apologies) (顺便说一句,我们在2014年,所以我无法在2008年测试此-抱歉)
SELECT * INTO #Demo FROM (VALUES
(1,'name1',9),
(1,'name1',26),
(1,'name1',15),
(2,'name2',20),
(2,'name2',18),
(2,'name2',61)) A (Id,Value1,Value2)
SELECT
Id
,ISNULL(Name1, 0) Name1
,ISNULL(Name2, 0) Name2
FROM
( SELECT
ROW_NUMBER() OVER ( PARTITION BY Id ORDER BY Id ) rn
,Id
,Value1
,Value2
FROM
#Demo ) A
PIVOT ( MAX(Value2) FOR Value1 IN ( [Name1], [Name2] ) ) AS P;
Id Name1 Name2
----------- ----------- -----------
1 9 0
1 26 0
1 15 0
2 0 20
2 0 18
2 0 61
you can do case based aggregation
with group by
您可以使用
group by
case based aggregation
select id,
max(case when value1 ='name1' then value2 else 0 end) as name1,
max(case when value1 ='name2' then value2 else 0 end) as name2
from Table1
group by id, value1, value2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.