我有这张桌子:
CREATE TABLE tblTest
(
Id INT PRIMARY KEY NOT NULL,
Weight INT NULL,
Batch INT NULL,
t_stamp DATETIME NULL
);
让我们假设它充满了价值观:
INSERT INTO BatchDataWillieNelson (WT401_Raw, Batch_Done_Signal,
Batch_Number, t_stamp)
VALUES (31, 3994, 2, '2023-12-05 06:19:58.990'),
(32, 4052, 2, '2023-12-05 06:37:24.883'),
(33, 4000, 5, '2023-12-05 08:44:09.780'),
(34, 4058, 5, '2023-12-05 08:58:59.683'),
(35, 4032, 8, '2023-12-05 11:18:11.727'),
(36, 3983, 11, '2023-12-05 13:20:35.167'),
(37, 4013, 11, '2023-12-05 13:33:54.877'),
(38, 3993, 14, '2023-12-05 15:29:50.060'),
(39, 3470, 14, '2023-12-05 15:48:51.053'),
(40, 3996, 14, '2023-12-05 17:20:09.893'),
(41, 3348, 14, '2023-12-05 17:39:22.477'),
(42, 3993, 20, '2023-12-05 19:48:42.117'),
(43, 4054, 20, '2023-12-05 20:09:12.217'),
(44, 3991, 23, '2023-12-05 22:55:45.020'),
(45, 4065, 23, '2023-12-05 23:16:12.077'),
(46, 3993, 26, '2023-12-06 02:56:29.713'),
(47, 4033, 26, '2023-12-06 03:12:24.483'),
(48, 3982, 26, '2023-12-06 06:06:45.720'),
(49, 4075, 26, '2023-12-06 06:35:05.197'),
(50, 3994, 4, '2023-12-06 08:02:58.887'),
(51, 3029, 4, '2023-12-06 08:28:21.260'),
(52, 3982, 7, '2023-12-06 09:49:23.497'),
(53, 4038, 7, '2023-12-06 10:12:41.707')
我正在使用 SQL Server 2008。我有一个表,其中有错误写入的额外记录。我需要删除这些。
我需要根据
Weight
的分组来评估 Batch_Number
列的最大值。同一个Batch_Number
可以多次使用。因此,在没有对表进行排序的情况下,我尝试查找 Batch_Number
中的更改,并将这些行视为一个组来进行评估,而不必遍历每条记录。
预期结果:
身份证 | 重量 | 批量 | t_邮票 |
---|---|---|---|
32 | 4052 | 2 | '2023-12-05 06:37:24.883' |
34 | 4058 | 5 | '2023-12-05 08:58:59.683' |
35 | 4032 | 8 | '2023-12-05 11:18:11.727' |
37 | 4013 | 11 | '2023-12-05 13:33:54.877' |
40 | 3996 | 14 | '2023-12-05 17:20:09.893' |
43 | 4054 | 20 | '2023-12-05 20:09:12.217' |
49 | 4075 | 26 | '2023-12-06 06:35:05.197' |
50 | 3994 | 4 | '2023-12-06 08:02:58.887' |
53 | 4038 | 7 | '2023-12-06 10:12:41.707' |
WITH MaxWeightPerBatch AS (
SELECT Batch_Number, MAX(Weight) AS MaxWeight
FROM tblTest
GROUP BY Batch_Number
)
DELETE FROM tblTest
WHERE (Batch_Number, Weight) NOT IN (
SELECT Batch_Number, MaxWeight
FROM MaxWeightPerBatch
);
找到每个 Batch_Number 组的最大权重,然后从 tblTest 中删除在各自的 Batch_Number 组内没有最大权重的行。
删除存在具有相同批次号和更高权重/信号的另一行的所有行。
delete from batchdatawillienelson
where exists
(
select null
from batchdatawillienelson other
where other.batch_number = batchdatawillienelson.batch_number
and other.batch_done_signal > batchdatawillienelson.batch_done_signal
);
如果您的 RDBMS 支持直接对表表达式进行操作,例如 SQL Server,则以下是另一种简单的方法:
delete from d
from (
select *, Row_Number() over(partition by batch order by weight desc) rn
from t
)d
where rn > 1;
参见 Fiddle 演示