在 SQL 中取消旋转 table 时获取存在值的列的位置
get the positon of a column where value exists while unpivoting the table in SQL
我试图在 SQL 服务器
中对列 col2、col3、col4 进行逆透视时获取值的列位置
df1
col1 col2 col3 col4
1 AAA BBB
2 ABC CCC DDD
result
col1 [All] [position]
1 AAA 1
1 BBB 2
2 ABC 1
2 CCC 2
2 DDD 3
我可以使用以下
取消 table 的旋转
SELECT a.col1, a.[all]
from df1 as t
UNPIVOT
(
[all] for col_nm in (
col2, col3, col4
) as a
您可以尝试以下 - 使用 row_number()
SELECT a.col1, a.[all],row_number() over(partition by a.col1 order by a.[all]) as position
from df1 as t
UNPIVOT
(
[all] for col_nm in (
col2, col3, col4
) as a
试试这个
select * from (
select col1,1 as position , col2 as [All] from [Table]
Union
select col1,2 as position, col3 as [All] from [Table]
Union
select col1,3 as position, col4 as [All] from [Table] )
where [all] is not null;
如果您只需要知道它来自哪一栏,我认为您可以简单地将 col_nm 包含到您的 select 语句中:
SELECT a.col1
,a.[all]
,a.col_nm
FROM df1 AS t UNPIVOT([all] FOR col_nm IN(col2, col3, col4)) AS a;
如果您需要知道列索引号 - 那么根据上面的内容应该很容易 - 也许对列名进行 switch-case 检查;或者,
如果这是物理的或临时的 table,您可以使用 sys.tables 和 sys.columns 返回以根据列名查找列索引 (columnId)。
您可以使用 APPLY
:
SELECT df1.col1, dff.*
FROM df1 as df CROSS APPLY
( VALUES (col2, 1), (col3, 2), (col4, 3) ) dff([All], [Position])
WHERE dff.[All] IS NOT NULL;
我试图在 SQL 服务器
中对列 col2、col3、col4 进行逆透视时获取值的列位置df1
col1 col2 col3 col4
1 AAA BBB
2 ABC CCC DDD
result
col1 [All] [position]
1 AAA 1
1 BBB 2
2 ABC 1
2 CCC 2
2 DDD 3
我可以使用以下
取消 table 的旋转SELECT a.col1, a.[all]
from df1 as t
UNPIVOT
(
[all] for col_nm in (
col2, col3, col4
) as a
您可以尝试以下 - 使用 row_number()
SELECT a.col1, a.[all],row_number() over(partition by a.col1 order by a.[all]) as position
from df1 as t
UNPIVOT
(
[all] for col_nm in (
col2, col3, col4
) as a
试试这个
select * from (
select col1,1 as position , col2 as [All] from [Table]
Union
select col1,2 as position, col3 as [All] from [Table]
Union
select col1,3 as position, col4 as [All] from [Table] )
where [all] is not null;
如果您只需要知道它来自哪一栏,我认为您可以简单地将 col_nm 包含到您的 select 语句中:
SELECT a.col1
,a.[all]
,a.col_nm
FROM df1 AS t UNPIVOT([all] FOR col_nm IN(col2, col3, col4)) AS a;
如果您需要知道列索引号 - 那么根据上面的内容应该很容易 - 也许对列名进行 switch-case 检查;或者,
如果这是物理的或临时的 table,您可以使用 sys.tables 和 sys.columns 返回以根据列名查找列索引 (columnId)。
您可以使用 APPLY
:
SELECT df1.col1, dff.*
FROM df1 as df CROSS APPLY
( VALUES (col2, 1), (col3, 2), (col4, 3) ) dff([All], [Position])
WHERE dff.[All] IS NOT NULL;