我有一个表,包括列id(键),符号,方向,范围,价格,百分比。我想删除符号,方向,价格和百分比与最低范围相同的数据。我该如何做到这一点?
我一直试图改变这句话:DELETE
FROM aw
WHERE id not in (select min(id) from aw group by symbol, direction, price, percent);
让事情发挥作用。
答案 0 :(得分:2)
尝试使用exists
子句:
DELETE FROM aw
WHERE
exists (
select
1
from
(select symbol, direction, price, percent, min(range) as minrange from aw
group by symbol, direction, price, percent) aw2
where
aw2.symbol = aw.symbol
and aw2.direction = aw.direction
and aw2.price = aw.price
and aw2.percent = aw.percent
and aw2.minrange = aw.range
)
答案 1 :(得分:2)
以下是 aw 表的示例数据。根据您的描述,我认为您要丢弃ID
值为2,3和5的行。
ID symbol direction range price percent
1 a x 15 10 5
2 a x 20 10 5
3 b y 40 50 5
4 b y 10 50 5
5 a x 15 10 5
确定symbol
,direction
,price
和percent
的每个组合的最小范围值。
<强> qryMinRanges 强>:
SELECT
aw.symbol,
aw.direction,
aw.price,
aw.[percent],
Min(aw.range) AS MinOfrange
FROM aw
GROUP BY
aw.symbol,
aw.direction,
aw.price,
aw.[percent];
...给出了这个结果集:
symbol direction price percent MinOfrange
a x 10 5 15
b y 50 5 10
确定每个最小范围的最小ID
。
<强> qryMinID_forMinRanges 强>:
SELECT
q.symbol,
q.direction,
q.price,
q.[percent],
q.MinOfrange,
Min(aw.ID) AS MinOfID
FROM
qryMinRanges AS q
INNER JOIN aw
ON
(q.MinOfrange = aw.range)
AND (q.[percent] = aw.[percent])
AND (q.price = aw.price)
AND (q.direction = aw.direction)
AND (q.symbol = aw.symbol)
GROUP BY
q.symbol,
q.direction,
q.price,
q.[percent],
q.MinOfrange;
...给出了这个结果集:
symbol direction price percent MinOfrange MinOfID
a x 10 5 15 1
b y 50 5 10 4
因此 qryMinID_forMinRanges 应该代表您要保留的行。最终,您将删除其SELECT
查询,以确认您的目标是删除正确的记录。
SELECT
aw.ID,
aw.symbol,
aw.direction,
aw.range,
aw.price,
aw.[percent]
FROM aw
WHERE aw.ID Not In
(SELECT MinOfID FROM qryMinID_forMinRanges);
...这给了我这个结果集:
ID symbol direction range price percent
2 a x 20 10 5
3 b y 40 50 5
5 a x 15 10 5
因此,如果看起来正确,请将其更改为DELETE查询。
DELETE *
FROM aw
WHERE
(((aw.ID) Not In
(SELECT MinOfID FROM qryMinID_forMinRanges)));
在DELETE之后,db引擎不需要*
。但是,如果要使用查询设计器的预览,则需要为其指定要显示的字段规范。
如果我在此处搞砸了任何细节,请采取预防措施来保护您的数据。备份很好。 : - )