获取在SQL中取消激活表时存在值的列的位置

获取在SQL中取消激活表时存在值的列的位置,sql,sql-server,tsql,unpivot,Sql,Sql Server,Tsql,Unpivot,我在SQL server中对col2、col3、col4列执行取消PIVOT操作时,试图获取值的列位置 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

我在SQL server中对col2、col3、col4列执行取消PIVOT操作时,试图获取值的列位置

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
我可以使用以下命令取消打印表格

SELECT a.col1, a.[all]
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;



如果您只需要知道它来自哪个列,我认为您可以简单地将列包含在select语句中:

SELECT a.col1
      ,a.[all]
      ,a.col_nm
FROM   df1 AS t UNPIVOT([all] FOR col_nm IN(col2, col3, col4)) AS a;
如果您需要知道列索引号,那么基于上面的内容应该很容易,也许可以对列名进行切换大小写检查;或者


如果这是一个物理表或临时表,您可以使用sys.tables和sys.columns返回,以根据列名查找列索引(columnId)。

您可以使用
应用

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;

你是怎么在col1上得了3分的?请提供你的逻辑too@Avi对不起,那是个打字错误。我不知道你所说的逻辑是什么意思,但我已经提供了如何取消激活该表的代码。试着阅读本文,它可能会对你有所帮助。:)这似乎不起作用-当使用OrderBy the row_number()时,可能无法为您提供正确的列索引…@Rex,您最好尝试一下,并告诉我它不起作用,我现在尝试了,并确认它不起作用-您可以在将第一个值“AAA”调整为“ZZZ”后尝试查询,您将看到列编号变为3,因为我的订单是最后一个!
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;