繁体   English   中英

SQL选择第一列以匹配单行中多列的条件

[英]SQL Select the first Column to match criteria of Many columns in a single row

美好的一天,

所以我坚持使用SQL查询,其中我查询的表有多个连续列,例如

Property1,
Property2,
Property3,
Property4,
Property5
..etc

现在,在相同的命名约定中有大约64列降序。 它们是varchar类型,并用一个“Y”或“N”表示布尔函数。(不是我的设计)

现在,我被困在我的查询中,我需要返回在单个记录中标记为“Y”的First Property列。

我已经四处寻找,但不可能在别处问过同样的问题。也许我只是错过了它?

如果有人提示我跟随等等,真的很感激吗? 提前致谢!

基本思想是连接一个字符串中的所有字段,然后找到第一个出现的Y的索引,并将字段标签形成为PROPERTY + FIRST OCCURRENCE INDEX 如果未找到Y则此查询中出现PROPERTY0 ,您可以使用CASE语句处理此问题。

SQLFiddle演示

select id,
       'PROPERTY'+
       CONVERT(VARCHAR(10),CHARINDEX('Y',property1+property2+property3)) 

from T

那个设计太可怕了。 但这应该工作:

SELECT CASE WHEN Property1 = 'Y' THEN 'Property1'
            WHEN Property2 = 'Y' THEN 'Property2'
            [...]
       ELSE 'None'
       END

你可以考虑转移

declare @t table(id int identity(1,1), Property1 char(1),
Property2 char(1),
Property3 char(1),
Property4 char(1),
Property5 char(1))

insert @t values('N', 'Y', 'Y', 'N', 'Y')
insert @t values('N', 'N', 'Y', 'N', 'Y')
insert @t values('N', 'N', 'N', 'N', 'Y')

;with a as
(
  select *, row_number() over (partition by id order by id) position from @t
  unpivot
  (Property FOR colname IN           
  ([Property1], [Property2], [Property3], [Property4], 
   [Property5]/*include more properties here*/) ) AS unpvt  
)
select t.id, coalesce(colname, 'Not found') colname
from @t t
outer apply 
(select top 1 id, colname, position
from a where Property = 'Y'
and t.id = id
order by id
) x

尝试这个:

select 
CASE WHEN QryGroup1 = 'Y' then 'QryGroup1'
WHEN QryGroup2 = 'Y' then 'QryGroup2'
WHEN QryGroup3 = 'Y' then 'QryGroup3'
WHEN QryGroup10 = 'Y' then 'QryGroup10'
else ''
end as [SelectedBP]
from OCRD

这可能也有效:

SELECT CHARINDEX ( 'Y' , CONCAT(Property1,Property2,...,Property64) )

它返回列的数字索引,它的优点是您可以定义基于函数的索引以加快查询速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM