需要SQL查询与三个值匹配

时间:2018-08-27 09:55:33

标签: sql sql-server

我有一个如下表

Go functions can be exported for use by C code in the following way:

我需要查询以选择具有全部3个CAccountID CID NetworkID 1 1 1 2 1 2 3 2 1 4 2 2 5 2 3 6 3 1 7 3 2 8 3 3 9 4 1 10 4 2 的所有CID,而无需仅显示1个和2个NetworkID(1,2,3)

输出应如下所示,

NetworkID

4 个答案:

答案 0 :(得分:1)

您可以将GROUP BYJOIN结合使用:

select t.*
from table t inner join
     ( select cid 
       from table
       where NetworkID in (1,2,3)
       group by cid
       having count(distinct NetworkID) = 3
     ) tt 
     on tt.cid  = t.cid; 

答案 1 :(得分:0)

尝试一下:

select * from my_table t
where exists(select 1 from my_table
             where CID = t.CID and NetworkID in (1,2,3)
             group by CID
             having count(*) = 3)

答案 2 :(得分:0)

尝试一下:

select * from <<tablename>> where cid in(select cid from <<tablename>> group by cid having count(*)=3).

在这里,子查询将返回表中有3行的所有thouse cid。

或者,如果您有更多的网络ID,则使用 INTERSECT 运算符可能会有所帮助:

select * from <<tablename>> where cid in (
   select cid from <<tablename>> where NetworkID=1
   INTERSECT 
   select cid from <<tablename>> where NetworkID=2
   INTERSECT
   select cid from <<tablename>> where NetworkID=3
);

INTERSECT运算符基本上返回查询中所有常见的行。因此,可以通过这种方式处理您的数据不可预测性

答案 3 :(得分:0)

尝试xml路径。

@Override

CTE演示:

SELECT *
FROM Table_Name B
WHERE (SELECT [text()] = A.Network FROM Table_Name A WHERE A.CID = B.CID 
ORDER BY CID, CAAccount FOR XML PATH('')) = 123

输出:

; WITH CTE(CAAccount, CID, Network) AS
(
SELECT 1 , 1, 1 UNION ALL
SELECT 2 , 1, 2 UNION ALL
SELECT 3 , 2, 1 UNION ALL
SELECT 4 , 2, 2 UNION ALL
SELECT 5 , 2, 3 UNION ALL
SELECT 6 , 3, 1 UNION ALL
SELECT 7 , 3, 2 UNION ALL
SELECT 8 , 3, 3 UNION ALL
SELECT 9 , 4, 1 UNION ALL
SELECT 10, 4, 2
) SELECT *
FROM CTE B
WHERE (SELECT [text()] = A.Network FROM CTE A WHERE A.CID = B.CID ORDER BY CID, CAAccount FOR XML PATH('')) = 123