我有一个名为Details的表。样本记录如下
ID PNO ActionsTaken
52101 2 Received
52101 5 Received
52101 3 Received
52101 3 Send To HO
52101 3 Send to RD
52101 7 Received
52101 8 Received
35501 2 Received
35501 7 Received
35501 7 Send To HO
我需要按如下方式查询记录
ID PNO ActionsTaken
52101 2 Received
52101 5 Received
52101 7 Received
52101 8 Received
35501 2 Received
ActionTaken仅“收到”没有获得“发送到HO”或“发送到RD”等其他操作。
答案 0 :(得分:1)
表格包含 7条记录,其中 [ActionsTaken] 为“已收到”。但结果集只需 5条记录, [ActionsTaken] 为“已收到”,这意味着结果需要 [ActionsTaken] 为“已收到” “而且 [ID] 和 [PNO] 不应该只有”已接收“以外的 [ActionsTaken] 。
SELECT T1.*
FROM [Table] T1
WHERE T1.ActionsTaken = 'Received'
AND NOT EXISTS (
SELECT TOP 1 NULL
FROM [Table] T2
WHERE T2.ID = T1.ID
AND T2.PNO = T1.PNO
AND T2.ActionsTaken <> 'Received'
)
答案 1 :(得分:0)
您的查询是
Select * from Details where ActionsTaken = 'Received'
答案 2 :(得分:0)
;WITH CTE AS (
select ID,PNO from @Table1 where ActionsTaken <> 'Received'
)
select T.*
from @Table1 T
left join CTE c on t.ID=c.ID AND t.PNO = c.PNO
WHERE c.ID IS NULL
说明: -
在代码段中,我使用CTE获取所有没有值&#39;已接收的记录的ID,PNO。 所以在这种情况下,CTE中将有2条记录
ID PNo
52101 3
35501 7
在下一个sql语句中,它将与cte一起加入主表。 如果没有WHERE条件(c.ID IS NULL),结果集将为
ID PNO ActionsTaken ID PNo
52101 2 Received NULL NULL
52101 5 Received NULL NULL
52101 3 Received 52101 3
52101 3 Send To HO 52101 3
52101 3 Send to RD 52101 3
52101 7 Received NULL NULL
52101 8 Received NULL NULL
35501 2 Received NULL NULL
35501 7 Received 35501 7
35501 7 Send To HO 35501 7
现在,当应用WHERE条件(c.ID IS NULL)时,我们将获得ActionTaken的记录仅为&#34;已收到&#34;。
答案 3 :(得分:0)
cte不适用于我的sql,所以,没有cte:
SELECT DISTINCT [d1]。* FROM @Details AS [d1] LEFT JOIN @Details AS [d2] ON [d1]。[id] = [d2]。[id] AND [d1]。[pno] = [d2]。[pno]和[d2]。[ActionsTaken]&lt;&gt; “收到” WHERE [d1]。[ActionsTaken] ='收到'和[d2]。[id] IS NULL;
答案 4 :(得分:0)
@juozas Op并不想拍摄不同的唱片,他只是想要收到带有actions_taken的唱片,所以这对于这个问题是完美的:
SELECT ID,PNO,ActionsTaken FROM Details WHERE ActionsTaken = 'Received';