仅当某些条件与另一个表匹配时才返回行

时间:2018-06-21 13:12:33

标签: sql sql-server tsql

我想要一个SQL查询,该查询返回一个用户列表,但前提是他们只有一个链接而不是另一个链接。

  • 表1链接到表2的用户。agreementid= Agreements.id,它可以链接多次,因为用户可以链接到不同的协议

  • 表1中的所有用户仅具有指向产品为AggregationAgreement的协议的链接,如果用户具有指向2+协议ID的链接,并且任何链接均指向ServiceAgreement,则不应退回

所以我有2个表: 表1-用户

USER     AGREEMENTID
--------------------
USER1    1
USER2    3
USER1    3
USER3    3
USER3    4
USER4    1

表2协议

ID   PRODUCT
-------------------------
1    ServiceAgreement
2    ServiceAgreement
3    AggregationAgreement
4    AggregationAgreement
5    ServiceAgreement

因此,对于上述示例的结果,我只希望返回USER2和USER3。
USER 1有两个链接,但其中之一是ServiceAgreement,因此不应在结果中返回它。
USER 2仅具有1个聚合协议的链接,因此应在结果中返回。
USER 3有两个链接,但都指向AggregationAgreement,因此应在结果中返回该链接。
USER 4有一个链接,但它指向ServiceAgreement,因此不应在结果中返回。

希望一切都有意义,一如既往地感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

尝试一下:

select * 
from users u
where exists 
(
    select 1 
    from agreements a 
    where u.agreementid=a.id and a.product='AggregationAgreement'
)
and not exists
(
    select 1 
    from agreements a2 
    where u.agreementid=a2.id and a2.product<>'AggregationAgreement'
)

答案 1 :(得分:1)

这将返回带有协议的用户,但不包括链接有ServiceAgreement的用户。

SELECT USERS.[UserName]
     , AGREEMENTS.[AgreementId]
     , AGREEMENTS.[Product]
FROM   USERS
       INNER JOIN AGREEMENTS
           ON AGREEMENTS.[AgreementId] = USERS.[AgreementId]
WHERE  USERS.[UserName] NOT IN
           (
               SELECT USERS.[UserName]
               FROM   USERS
                      INNER JOIN AGREEMENTS
                          ON AGREEMENTS.[AgreementId] = USERS.[AgreementId]
               WHERE  AGREEMENTS.[Product] = 'ServiceAgreement'
           )

答案 2 :(得分:1)

您还可以使用以下查询

wp_enqueue_script('main-js', get_theme_file_uri('/js/scripts-bundled.js'), array('jquery'), '1.2', true);

答案 3 :(得分:1)

使用除:

declare @Users table ([User] nvarchar(10), [AGREEMENTID] int)
insert into @Users values 
  ('USER1', 1)
, ('USER2', 3)
, ('USER1', 3)
, ('USER3', 3)
, ('USER3', 4)
, ('USER4', 1)

declare @Agreements table ([ID] int, [Product] nvarchar(100))
insert into @Agreements values
  (1, 'ServiceAgreement')
, (2, 'ServiceAgreement')
, (3, 'AggregationAgreement')
, (4, 'AggregationAgreement')
, (5, 'ServiceAgreement')

select u.[User] from @Users u inner join @Agreements a on u.AGREEMENTID = a.ID and a.Product = 'AggregationAgreement'
except
select u.[User] from @Users u inner join @Agreements a on u.AGREEMENTID = a.ID and a.Product = 'ServiceAgreement'
相关问题