【问题标题】:Find groups match IN condition list incompletely查找与 IN 条件列表不完全匹配的组
【发布时间】:2017-08-03 12:18:15
【问题描述】:

我目前正在处理一个存储过程,我需要编写一个查询,它选择 all GroupIds that don't have all TypeIds .

关于这个例子:

Id | GroupId | TypeId |
---+---------+--------+
1  |  1      |  1     | 
2  |  1      |  2     |
3  |  1      |  3     |
4  |  2      |  1     | 
5  |  2      |  2     |
6  |  3      |  1     |
7  |  3      |  2     | 
8  |  3      |  3     |
9  |  4      |  2     |

我想选择 GroupIds 2 和 4,因为这些组没有全部三个 TypeIds 1、2 和 3。GroupId 4 只有 TypeId 2 而 GroupId 2 只有 TypeIds 1 和 2。

我当前的查询看起来像这样,但不起作用:

SELECT [A].ActorPoolId
FROM [OfferCatalog].[Actor] [A]
WHERE [A].ActorTypeId IN ('1', '2', '3')

你知道如何解决这个问题吗?

【问题讨论】:

    标签: sql sql-server tsql sql-server-2014


    【解决方案1】:

    您可以使用group by + having 组合:

    select [A].ActorPoolId
    from [OfferCatalog].[Actor] [A]
    where [A].ActorTypeId in ('1', '2', '3') 
    group by [A].ActorPoolId 
    having count(distinct [A].ActorTypeId) < 3
    

    如果ActorTypeId 对于每个ActorPoolId 都是唯一的,您可以省略使用distinct

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 2022-12-03
      • 2020-01-09
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多