我有一张桌子,我试图找到一组特定的记录。这是我的桌子的样子......
tblA
ID VouchID Action Amount
1 177-17 Add 700
2 177-17 Update 1
3 198-01 Add 600
4 198-01 Update 620
所以这里发生的是,如果记录被取消/删除,则操作将为“更新”,金额将更新为1.换句话说,VouchID = 177-17,不会被计算/被选中在这个查询...
我希望在这里做的只是选择记录,没有Amount = 1的相应更新记录
Select distinct vouchID where Action='add'
但是,此查询不会考虑具有“更新”操作的VoucherID。更新操作可以应用于两个实例,在VouchID 177-17中,amount = 1 on action ='update',这意味着,ADD操作不计算,这几乎就像我们一起删除了记录一样(它只是为了保持记录中)。在VoucherID = 198-01,更新行和金额= 620的情况下的另一个更新意味着金额更新了20到620,我希望能够在我的最终重新看到该记录
上表所需的最终结果:
ID VouchID Action Amount
3 198-01 Add 600
答案 0 :(得分:2)
您可以使用LEAD
(SQL Server 2012及更高版本):
WITH cte AS (
SELECT *, LEAD(Amount) OVER(PARTITION BY VouchID ORDER BY ID) AS next_amount
FROM table
)
SELECT *
FROM cte
WHERE (next_amount <> 1 OR next_amount IS NULL) AND Action='add';
修改强>
非递归CTE总是可以用简单的子查询替换:
SELECT *
FROM (SELECT *,
LEAD(Amount) OVER(PARTITION BY VouchID ORDER BY ID) AS next_amount
FROM table) sub
WHERE (next_amount <> 1 OR next_amount IS NULL) AND Action='add';
修改强>
使用EXISTS
:
SELECT *
FROM table t1
WHERE Action='add'
AND NOT EXISTS (SELECT TOP 1
FROM table t2
WHERE t1.VouchId = t2.VouchId
AND Action='Update'
AND Amount = 1
ORDER BY ID ASC);
答案 1 :(得分:2)
我希望在这里做的只是选择记录,没有 相应的更新记录,金额= 1
使用NOT EXISTS()似乎很容易:
Select distinct vouchID FROM MyTable t1 where Action='add'
AND NOT EXISTS(SELECT * FROM MyTable t2
WHERE Action='Update'
AND Amount=1
AND t2.VouchId=t1.VouchId
答案 2 :(得分:1)
您使用的是SQL Server 2008还是更好?如果你是,我会尝试类似的东西:
SELECT
ID, vouchID, Action, Amount
FROM tblA s
WHERE
Action='add'
AND NOT EXISTS(Select 1 from tblA l where l.vouchID = s.vouchID and l.Action = 'Update' and l.Amount = 1);