我有一个名为TableA的表,其中有很多行。下面给出了示例结构
CID int, Col1 int, Col2 int, Col3 int, Col4 int
当我运行查询时(例如,当CID = 5时),我只会得到Col1,Col2等具有不同值的一行。
我想获取行值为-1的列名的数字。
为了更加清晰
CID, Col1, Col2 , Col3 , Col4
5 0 -1 0 -1
在此示例中,我应得到的结果为
MyRes
2
4
有什么办法可以实现
答案 0 :(得分:0)
我得到了答案
declare @ID int
set @ID = 1
select substring( T1.ColName, 2, LEN(T1.ColName)) as MyRes from (
select
Col.value('local-name(.)', 'varchar(10)') as ColName
from (select *
from TableA
for xml path(''), type) as T(XMLCol)
cross apply
T.XMLCol.nodes('*') as n(Col)
where Col.value('.', 'varchar(10)') = '-1'
)T1
答案 1 :(得分:0)
您可以使用unpivot
,然后根据结果值-1
过滤记录。
; with cte as (
select CID, result, col from
(
select * from table
) as t
unpivot
(
result for col in ( Col1, col2, col3, col4 )
) as p
)
select CId, col from cte where result = -1
只需做一些家庭作业,即可从列名中获取数字部分。
如果您发现该部分有任何问题,请评论我也会这样做,但让我们先尝试一下。