我有一个名为 dbo.Tag 的表,如下所示:
Counter|TagValue
1 |CREATED
2 |REMOVED
我只想从另一个名为 dbo.Transactions
的表中获取与 dbo.Tag 相匹配的记录。Counter|TagValue
1 |CREATED
1 |UPLOADED
2 |CREATED
2 |REMOVED
3 |DELETED
4 |CREATED
4 |REMOVED
所以,我的预期输出是这样的:
Counter|TagValue
2 |CREATED
2 |REMOVED
4 |CREATED
4 |REMOVED
我尝试做的是以下查询:
SELECT COUNTER FROM dbo.Transactions IN (SELECT * from dbo.Tag)
但是它返回了这个,不是我所需要的: 第一个记录“ Counter 1”不应存在,因为它没有“ REMOVED” TagValue
Counter|TagValue
1 |CREATED
2 |CREATED
2 |REMOVED
4 |CREATED
4 |REMOVED
执行上述操作的正确查询是什么?
答案 0 :(得分:2)
与过滤器结合使用
SELECT a.COUNTER,a.tagvalue FROM dbo.Transactions a
join dbo.Tag b on a.tagvalue=b.tagvalue
where a.tagvalue in ('CREATED','REMOVED')
group by a.COUNTER,a.tagvalue
having count(distinct Tagvalue)=2)
答案 1 :(得分:1)
我认为这对您会有所帮助:
SELECT * FROM Transactions
WHERE Counter IN (
SELECT Counter AS CountOf
FROM Transactions AS T
WHERE T.TagValue IN (SELECT TagValue FROM dbo.Tag)
GROUP BY Counter
HAVING COUNT(*)>1)
答案 2 :(得分:0)
您正在寻找的是内部联接。试试以下查询。
SELECT A.COUNTER, A.TagValue
FROM dbo.Transactions A
INNER JOIN dbo.Tag B
ON A.COUNTER = B.COUNTER
AND A.TagValue= B.TagValue
答案 3 :(得分:0)
以下查询可以为您提供帮助:
SELECT TA.*
FROM dbo.Transactions TA
JOIN ( SELECT [Counter]
FROM dbo.Transactions
WHERE TagValue IN (SELECT TagValue FROM dbo.Tag)
GROUP BY [Counter]
HAVING COUNT(DISTINCT TagValue) = 2
) AS SQ ON SQ.[Counter] = TA.[Counter]