我想根据来自不同表的条件从表中删除行。如果Sales
和Final_Sales
表中的所有行都相同,我想删除Sales
表中的行。以下是我正在尝试的,
我的t-sql
声明,
delete
Sales
from
Sales
inner join
Final_Sales on Sales.[time] = Final_Sales.[time]
AND Sales.terminal_id = Final_Sales.terminal_id
-- Condition goes here. Check if they have the same records
WHERE time, terminal_id IN (select
time, terminal_id count(*)
from
Final_Sales
group by
time, terminal_id
having
count(*) = 1)
这不起作用。如何根据另一个表中的条件删除表中的记录?
任何帮助将不胜感激。
答案 0 :(得分:1)
SQL Server不允许IN
operator左侧有多个表达式。 IN
运算符语法为:
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
test_expression
是任何表达方式。 expression是“SQL Server数据库引擎评估以获取单个数据值的符号和运算符的组合。” (强调我的)
查询可以先收集选定的Final_Sales行,然后删除匹配的Sales行。一种方法是使用CTE:
;with FinalSales (time, terminal_id, count) as
(
select time, terminal_id, count(*)
from Final_Sales
group by time, terminal_id
having count(*) = 1
)
delete Sales
from FinalSales
inner join Sales
on Sales.[time] = FinalSales.[time]
and Sales.terminal_id = FinalSales.terminal_id