我有一个包含多个具有相同标识符的记录的数据库。我想删除其中一条记录。
OrderNum Cost
10001 254
10002 343
10002 300
10003 435
10003 323
对于上表,假设我只想删除具有较小成本的重复订单号的记录。例如:记录10002,保持成本为343,删除较小的300。
这是我提出的查询,但是如果表中的其他地方存在类似的成本,我使用成本来识别重复,这是不好的。
DELETE Orders.*
FROM Orders
WHERE (cost In
(Select min(cost) FROM Orders
GROUP BY [OrderNum] HAVING Count(*) > 1))
如何使用订单号进行查询并删除具有重复值的较小值?
答案 0 :(得分:2)
我将分阶段解释解决方案:
SELECT OrderNum, Min(Cost) as MinCost
FROM Orders
GROUP BY OrderNum
HAVING COUNT(*) > 1
这将返回您要删除的记录:
OrderNum MinCost
10002 300
10003 323
以下是使用子SELECT
s:
SELECT *
FROM
(
SELECT OrderNum, Min(Cost) as MinCost
FROM Orders
GROUP BY OrderNum
HAVING COUNT(*) > 1
) M
我们希望将标记为删除记录的表连接回Orders
表,实现此目的的一种方法是使用EXISTS语句:
SELECT *
FROM Orders O
WHERE EXISTS (
SELECT *
FROM
(
SELECT OrderNum, Min(Cost) as MinCost
FROM Orders
GROUP BY OrderNum
HAVING COUNT(*) > 1
) M
WHERE O.OrderNum = M.OrderNum
AND O.Cost = M.MinCost
)
现在我们已经掌握了所需的SELECT
语句,我们将其转换为DELETE语句:
DELETE
FROM Orders O
WHERE EXISTS (
SELECT *
FROM
(
SELECT OrderNum, Min(Cost) as MinCost
FROM Orders
GROUP BY OrderNum
HAVING COUNT(*) > 1
) M
WHERE O.OrderNum = M.OrderNum
AND O.Cost = M.MinCost
)
如果您有大量数据,您可能希望创建一个索引来优化连接:
CREATE INDEX IX_Orders_001 ON Orders (OrderNum, Cost);
答案 1 :(得分:0)
你想要真正做到这样的事情:
Class<?> iAccessibilityServiceConnectionClass= Class.forName("android.accessibilityservice.IAccessibilityServiceConnection");
Class<?> serviceManagerClass = Class.forName("android.os.ServiceManager");
Class<?>[] classes = iAccessibilityServiceConnectionClass.getDeclaredClasses();
Class<?> stubClass = null;
for (Class c : classes) {
if (c.getSimpleName().equals("Stub")) {
stubClass = c;
}
}
Method asInterfaceMethod = stubClass.getMethod("asInterface", IBinder.class);
Method getServiceMethod = serviceManagerClass.getMethod("getService", new Class[]{String.class});
Method getDisableSelf = iAccessibilityServiceConnectionClass.getMethod("disableSelf");
Object getAccesibilityConnectionObject = asInterfaceMethod.invoke(null, getServiceMethod.invoke(serviceManagerClass, "accessibility"));
getDisableSelf.invoke(getAccesibilityConnectionObject);
但Access不像许多大型RDBMS那样支持这样的元组。
相反,你可以连接你的元组:
WHERE (ordernum, cost) IN (SELECT ordernum, min(cost) as cost FROM Orders GROUP BY OrderNum HAVING COUNT(*) > 1);
答案 2 :(得分:0)
这将删除所有重复项,但每个
最大的副本list.add(add(list.size(), E)
答案 3 :(得分:0)
您可以使用JOIN
删除每个OrderNum
的较小费用,如下所示:
DELETE Orders.*
FROM Orders
join (Select OrderNum, max(cost) as cost FROM Orders
GROUP BY [OrderNum] HAVING Count(*) > 1) as R
on Orders.OrderNum=R.OrderNum and Orders.cost < R.cost