【问题标题】:How to compare two sub queries in one sql statement如何在一个sql语句中比较两个子查询
【发布时间】:2014-01-07 19:46:23
【问题描述】:

我有一个表tbl_Country,其中包含名为IDName 的列。 Name 列有多个用逗号分隔的国家/地区名称,我希望传递多个国家/地区名称时的 id 与 Name 列值进行比较。我正在使用函数拆分国家/地区名称 - 示例查询如下所示:

@country varchar(50)

SELECT *
FROM   tbl_Country
WHERE  (SELECT *
        FROM   Function(@Country)) IN (SELECT *
                                       FROM   Function(Name))

tbl_country    

ID        Name
1         'IN,US,UK,SL,NZ'
2         'IN,PK,SA'
3         'CH,JP'

parameter @country ='IN,SA'

我必须得到

  ID 
   1
   2


NOTE:  The Function will split the string into a datatable

【问题讨论】:

  • 问题是:你想检索ID's where the combination 的传递的contries 或者你正在寻找所有ID's where any 的传递国家在吗?
  • 我正在寻找存在任何已通过国家/地区的所有 ID

标签: sql sql-server select stored-procedures subquery


【解决方案1】:

试试这个,

select a.id FROM   tbl_Country a inner join 
(SELECT country FROM   dbo.Function(@Country)) b on a.name=b.country

【讨论】:

    【解决方案2】:

    基本上,通过在单个列中指定多个值,您违反了1st NF。因此,以下方法可能不是一个好方法,但提供了您正在寻找的解决方案:

      declare @country varchar(50)= 'IN,SA'
      declare @counterend int
      declare @counterstart int =1
      declare @singleCountry varchar(10)
      set @counterend = (select COUNT(*) from fnSplitStringList(@country))
      create table #temp10(
      id int
     ,name varchar(50))
    
     while @counterstart<= @counterend
    
    begin
    
    ;with cte as (
    select stringliteral country
    , ROW_NUMBER() over (order by stringliteral) countryseq 
    from fnSplitStringList(@country))
    select @singleCountry = (select country FROM   cte where countryseq=@counterstart)
    
    insert into #temp10(id, name)
    select * from tbl_country t1
    where not exists (select id from #temp10 t2 where t1.id=t2.id)
    and name like '%' + @singleCountry +'%'
    
    set @counterstart= @counterstart+1
    
    end
    
    select * from #temp10
    
    begin drop table #temp10 end
    

    它是如何工作的:它拆分传递的字符串并对其进行排序。之后,它会遍历生成的每个 Value(country) 的所有记录,并将它们插入到 temptable 中。

    【讨论】:

      【解决方案3】:

      试试这个:

      SELECT * 
      FROM tbl_Country C 
      WHERE ',' + @country + ',' LIKE '%,' + C.Name + ',%';
      

      【讨论】:

      • @shah CONCAT() 函数不在数据库中
      【解决方案4】:

      试试这个

         SELECT * FROM tbl_Country C
          LEFT JOIN tbl_Country C1 ON C1.Name=C.Country
      

      【讨论】:

      • 名称不是表,它是 tbl_Country 表中的列
      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      相关资源
      最近更新 更多