SQL 中的 Return 条记录包含 IN 子句中的所有值

Return records in SQL that include all values from IN clause

如果标题不完全准确,我深表歉意,但我不确定如何准确表达我的问题。我只想 return 行,其中结果包括在特定列上分组的 IN 语句中的所有项目。所以我的查询是:

    SELECT [DRSY],
           [DRRT],
           [DRKY],
           [DRDL01]
      FROM dbo.f0005
     WHERE DRKY IN ('FC', 'OO', 'SH')

我想 return 记录 DRSY 和 DRRT 包含所有项目 'FC'、'OO'、'SH'。也许一张图片可以帮助说明这一点:

我唯一想要 returned 的行是 DRSY = '00' 和 DRRT = 'DT' 的行,因为这包括我指定的所有 3 个值。我尝试寻找不同的方法来使用 IN、EXISTS,甚至 ALL。

我相信这可以通过 GROUPING 来完成,然后确保 DISTINCT 计数等于搜索项的数量:

   SELECT [DRSY],
          [DRRT]
   FROM dbo.f0005
   WHERE DRKY IN ('FC', 'OO', 'SH')
   GROUP BY [DRSY], [DRRT]
   HAVING COUNT(DISTINCT DRKY) = 3;

编辑,重新确保项目计数保持同步

您可以做的是建立一个派生的 table 或包含所需值列表的 CTE (searchValues),然后您可以加入(而不是 IN)然后您将能够 COUNT searchValues 避免任何与计数值相关的维护问题。

WITH searchValues AS
(
    select val 
    from (values ('FC'), ('OO'), ('SH')) as s(val)
)
SELECT [DRSY],
       [DRRT]
   FROM dbo.f0005
   INNER JOIN searchValues s
   ON DRKY = s.val
   GROUP BY [DRSY], [DRRT]
   HAVING COUNT(DISTINCT DRKY) = (SELECT COUNT(val) FROM searchValues);

SqlFiddle here

怎么样

SELECT DRSY, DRRT, DRKY, DRDL01 FROM dbo.f0005 a
WHERE exists (
   SELECT * FROM dbo.f005 b WHERE DRKY = "FC" and a.DRSY = b.DRSY and a.DRRT = b.DRRT
)
AND exists (
   SELECT * FROM dbo.f005 c WHERE DRKY = "00" and a.DRSY = c.DRSY and a.DRRT = c.DRRT
)
AND exists (
   SELECT * FROM dbo.f005 d WHERE DRKY = "SH" and a.DRSY = d.DRSY and a.DRRT = d.DRRT
)

我对@StuartLC 的例子做了一些修改。这样我也可以包含 table 中的其他列。再次感谢斯图尔特!

    WITH drky_count
    AS (SELECT DR.DRSY,
               DR.DRRT,
               DR.DRKY,
               DR.DRDL01,
               COUNT (DR.DRKY) OVER (PARTITION BY DR.DRSY, DR.DRRT)
                  AS DRKY_COUNT
          FROM f0005 DR
         WHERE DR.DRKY IN ('FC', 'OO', 'SH'))
    SELECT  DRSY, DRRT, DRKY, DRDL01
      FROM drky_count
     WHERE DRKY_COUNT = (SELECT MAX (DRKY_COUNT) FROM drky_count)

你也可以用 intersect

SELECT [DRSY], [DRRT] FROM dbo.f0005 WHERE DRKY = 'FC'
INTERSECT
SELECT [DRSY], [DRRT] FROM dbo.f0005 WHERE DRKY = 'OO'
INTERSECT
SELECT [DRSY], [DRRT] FROM dbo.f0005 WHERE DRKY = 'SH'