返回SQL中包含IN子句

时间:2015-07-10 13:16:55

标签: sql sql-server tsql exists

道歉,如果标题不完全准确,但我不确定如何准确地说出我的问题。我想只返回行,其中结果包括在特定列上分组的IN语句中的所有项。所以我的问题是:

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

我想要返回记录,其中DRSY和DRRT包括所有项目' FC'' OO' SH' SH'也许一张图片有助于说明这一点:

Results where DRSY = 00 and DRRT = DT

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

4 个答案:

答案 0 :(得分:3)

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

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

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

你可以做的是建立一个包含所需值列表(searchValues)的派生表或CTE,然后你可以加入(而不是IN),然后你就可以了COUNTsearchValues来计算价值的任何维护问题。

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

答案 1 :(得分:1)

怎么样?
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
)

答案 2 :(得分:0)

我拿了@ StuartLC的例子并稍微改了一下。这样我也可以在表格中包含其他列。再次感谢Stuart!

    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)

答案 3 :(得分:0)

您也可以使用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'