[英]Convert a column values to column names SQL server
I have a table with below schema. 我有一个具有以下架构的表。 Would like to get results as in expected result in SQL server. 希望获得与SQL Server中预期结果相同的结果。 Pivot does not work as Value column is string. 由于“值”列为字符串,因此数据透视不起作用。 Please suggest efficient way to achieve this. 请提出实现此目标的有效方法。 Thanks! 谢谢!
Table: 表:
Dim Key(String) , Dim Value (String)
AB XY1
AB XY2
CD XY3
CD XY4
Expected Result 预期结果
New columns=> AB CD
Row values => XY1 XY3
XY2 XY4
You want row_number()
: 您想要row_number()
:
select max(case when key = 'ab' then Value end) as ab,
max(case when key = 'cd' then Value end) as cd
from (select t.*,
row_number() over (partition by key order by Value) as seq
from table t
) t
group by seq;
However, your pivot
version should also work with row_number()
. 但是,您的pivot
版本也应该与row_number()
。
EDIT : 编辑:
select tt.*
from (select t.*,
row_number() over (partition by [key] order by Value) as seq
from table t
) as t pivot
( max(value) for [key] in ([ab], [cd])
) tt;
Self join should work. 自我加入应该起作用。 However you did not provide the complete business requirements for the SQL. 但是,您没有提供SQL的完整业务需求。
Which result do you expect? 您期望哪个结果?
New columns=> AB CD
Row values => XY1 XY3
XY2 XY4
Or, 要么,
New columns=> AB CD
Row values => XY1 XY4
XY2 XY3
Or, 要么,
New columns=> AB CD
Row values => XY1
XY2
XY3
XY4
Your SQL would look like this, 您的SQL看起来像这样,
select ab.value as "AB", cd.value as "CD"
from (select * from t where key='ab') ab
,(select * from t where key='cd') cd
But the above SQL gives you this result, 但是上面的SQL给你这个结果,
New columns=> AB CD
Row values => XY1 XY3
XY2 XY3
XY1 XY4
XY2 XY4
You should make a little modification the SQL to your needs. 您应该根据需要对SQL进行一些修改。 Hope it help! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.