使用多个IN运算子的子查询

时间:2019-04-01 18:25:16

标签: sql sql-server sql-server-2008

我试图获取列表1中的所有ID,并使用列表1中的ID,我试图获取列表2中的所有值以及基于列表2中的值的计数。

DECLARE @Table1 AS TABLE (
    id int, 
    l1 varchar(20)
);

INSERT INTO @Table1 VALUES
(1,'sun'),
(2,'shine'),
(3,'moon'),
(4,'light'),
(5,'earth'),
(6,'revolves'),
(7,'flow'),
(8,'fire'),
(9,'fighter'),
(10,'sun'),
(10,'shine'),
(11,'shine'),
(12,'moon'),
(1,'revolves'),
(10,'revolves'),
(2,'air'),
(3,'shine'),
(4,'fire'),
(5,'love'),
(6,'sun'),
(7,'rises');

/*
OPERATION 1
fetch all distinct ID's that has values from List 1
List1
sun
moon
earth

Initial OUTPUT1:
distinct_id list1_value
1           sun
3           moon
5           earth
10          sun
12          moon
6           sun


OPERATION2
fetch all the id, count_of_list2_values, list2_values  
based on the id's that we recieved from OPERATION1

List2
shine
revolves

Expected Output:

id  list1-value count_of_list2_values, list2_values  
1     sun              1                 revolves
3     moon             1                 shine
5     earth            0                 NULL
10    sun              2                 shine,revolves
12    moon             0                 NULL
6     sun              1                 revolves
*/

我的查询: 这是我尝试过的

select id, count(l1),l1
from @table1
where id in ('shine','revolves') and id in ('sun','moon','earth')

如何实现这一目标。 我知道这应该是具有多个in的子查询。如何实现?

SQL小提琴链接: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=7a85dbf51ca5b5d35e87d968c46300bb foo foo

3 个答案:

答案 0 :(得分:1)

与此:

with 
cte as(
  select t1.id, t2.l1
  from table1 t1 left join (
    select * from table1 where l1 in ('shine','revolves')
  ) t2 on t2.id = t1.id
  where t1.l1 in ('sun','moon','earth')
),
cte1 as(
  select 
    c.id, 
    stuff(( select ',' + cte.l1 from cte where id = c.id for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '') col
  from cte c
)

select 
  id, 
  count(col) count_of_list2_values, 
  max(col) list2_values  
from cte1
group by id

第一CTE给出以下结果:

id | l1      
-: | :-------
 1 | revolves
 3 | shine   
 5 | null    
10 | shine   
10 | revolves
12 | null    
 6 | revolves

,第二个对这些结果进行操作以将l1的公用分组值连接起来。
最后,我对第二个CTE的结果使用group by id和夸张。

请参见demo
结果:

id | count_of_list2_values | list2_values  
-: | --------------------: | :-------------
 1 |                     1 | revolves      
 3 |                     1 | shine         
 5 |                     0 | null          
 6 |                     1 | revolves      
10 |                     2 | shine,revolves
12 |                     0 | null 

答案 1 :(得分:1)

如果您使用的是Sql Server 2017,则可以使用string_agg函数和outer apply运算符:

select
    l1.id,
    l1.l1,
    l2.cnt as count_of_list2_values,
    l2.l1 as list2_values  
from @Table1 as l1
    outer apply (
        select
            count(*) as cnt,
            string_agg(tt.l1, ',') as l1
        from @Table1 as tt
        where
            tt.l1 in ('shine','revolves') and
            tt.id = l1.id
    ) as l2
where
    l1.l1 in ('sun','moon','earth')

db fiddle demo

在以前的版本中,我不确定不为此创建特殊功能就可以汇总和计数一次。当然,您可以使用xquery来做到这一点,但这可能有点过大(至少我不会在生产代码中这样做):

select
    l1.id,
    l1.l1,
    l2.data.value('count(l1)', 'int'),
    stuff(l2.data.query('for $i in l1 return concat(",",$i/text()[1])').value('.','nvarchar(max)'),1,1,'')
from @Table1 as l1
    outer apply (
        select
            tt.l1
        from @Table1 as tt
        where
            tt.l1 in ('shine','revolves') and
            tt.id = l1.id
        for xml path(''), type
    ) as l2(data)
where
    l1.l1 in ('sun','moon','earth')

db fiddle demo

如果您不介意对表进行两次扫描/查找,则可以使用@forpas答案或执行以下操作:

with cte_list2 as (
    select tt.l1, tt.id
    from @Table1 as tt
    where
        tt.l1 in ('shine','revolves')
)
select
    l1.id,
    l1.l1,
    l22.cnt as count_of_list2_values,
    stuff(l21.data.value('.', 'nvarchar(max)'),1,1,'') as list2_values
from @Table1 as l1
    outer apply (
        select
            ',' + tt.l1
        from cte_list2 as tt
        where
            tt.id = l1.id
        for xml path(''), type
    ) as l21(data)
    outer apply (
        select count(*) as cnt
        from cte_list2 as tt
        where
            tt.id = l1.id
    ) as l22(cnt)
where
    l1.l1 in ('sun','moon','earth')

答案 2 :(得分:1)

有几种方法可以完成此操作。这是我的处理方式:

首先设置数据:

DECLARE @Table1 AS TABLE (
    id int, 
    l1 varchar(20)
) ;

INSERT INTO @Table1 VALUES
(1,'sun'),
(2,'shine'),
(3,'moon'),
(4,'light'),
(5,'earth'),
(6,'revolves'),
(7,'flow'),
(8,'fire'),
(9,'fighter'),
(10,'sun'),
(10,'shine'),
(11,'shine'),
(12,'moon'),
(1,'revolves'),
(10,'revolves'),
(2,'air'),
(3,'shine'),
(4,'fire'),
(5,'love'),
(6,'sun'),
(7,'rises') ;

由于这是已知列表,因此请按自己的设置设置“目标”数据。 (在SQL中,表的使用总是比不固定的列表好得多。糟糕,错字!我的意思是定界的列表。)

DECLARE @Targets AS TABLE (
    l2 varchar(20)
) ;

INSERT INTO @Targets VALUES
('sun'),
('moon'),
('earth') ;

操作1 获取具有列表1中的值的所有唯一ID (太阳,月亮,地球)

加入联接很容易:

SELECT Id
 from @Table1  t1
  inner join @Targets  tg
   on tg.l2 = t1.l1

操作2 获取所有ID,count_of_list2_values,list2_values
根据我们从OPERATION1收到的ID

如果我正确地遵循了所需的逻辑,那么(请先阅读“加入”注释):

SELECT
   tt.Id
   --  This next counts how many items in the Operation 1 list are not in the target list
   --  (Spaced out, to make it easier to compare with the next line)
  ,sum(       case when tg2.l2 is null then 1 else 0 end) 
   --  And this concatenates them together in a string (in later editions of SQL Server)
  ,string_agg(case when tg2.l2 is null then tt.l1 else null end, ', ')
 from @Table1 tt
  inner join (--  Operation 1 as a subquery, produce list of the Ids to work with
              select t1.id
               from @Table1  t1
                inner join @Targets  tg
                 on tg.l2 = t1.l1
             ) xx
   on xx.id = tt.id
  --  This is used to identify the target values vs. the non-target values
  left outer join @Targets    tg2
   on tg2.l2 = tt.l1
 --  Aggregate, because that's what we need to do
 group by tt.Id
 --  Order it, because why not?
 order by tt.Id