简体   繁体   English

在单个单元格中基于多个条件选择记录

[英]Selecting records based on multiple criteria in a single cell

I am working with a database that is set up to show multiple values, separated by commas as shown: 我正在使用一个数据库,该数据库设置为显示多个值,并用逗号分隔,如下所示:

txtSiblingsYearList
7,4
9,6
8,3,N
8,3,N
5,3
5,3

I need to be able to query this and only bring back records that have at least 2 of R, N, 1, 2, 3, 4, 5, 6 我需要能够对此进行查询,并且只带回至少具有R,N,1、2、3、4、5、6中的2个的记录

I am not sure if this is something that can be done given the way the data is stored within the database table. 我不确定这是否可以通过将数据存储在数据库表中的方式来完成。 Does anyone know a way to do this. 有谁知道做到这一点的方法。 My current query looks like: 我当前的查询如下所示:

    SELECT 
      [txtSchoolID]
      ,[txtTitle]
      ,[txtForename]
      ,[txtSurname]       
      ,[txtForm]
      ,[intNCYear]      
      ,[intFamily]      
      ,[txtSiblingsIDList]
      ,[txtSiblingsNameList]
      ,[txtSiblingsFormList]
      ,[txtSiblingsYearList]      
  FROM [iSAMS].[dbo].[TblPupilManagementPupils]
  Where (intSystemStatus = 1) 
  AND (intNCYear <7) 
  AND (txtSchoolID NOT LIKE txtSiblingsIDList)  
  Order By intFamily

Any help appreciated. 任何帮助表示赞赏。

You should not be storing lists of values in a comma-delimited string. 您不应将值列表存储在以逗号分隔的字符串中。 That is not the SQL way of doing things. 那不是SQL的处理方式。 The resulting queries cannot be optimized, and string functions are not SQL's forte. 结果查询无法优化,并且字符串函数不是SQL的优势。

If you are stuck with this format, you can add up the number of matches: 如果您坚持使用这种格式,则可以将匹配项总数相加:

where ( (case when ',' + txtSiblingsYearList + ',' like '%,R,%' then 1 else 0 end) +
        (case when ',' + txtSiblingsYearList + ',' like '%,N,%' then 1 else 0 end) +
        (case when ',' + txtSiblingsYearList + ',' like '%,1,%' then 1 else 0 end) +
        . . .
      ) >= 2

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

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