[英]How to Create a New Table with Distinct Values but selecting the Max from another column
我正在使用 Python 和 SQLite,我正在尝试将表复制到另一个表。 我有一个名为 InventoryNbr 的列,还有一个名为 IndexID 的列。 其他列此时无关紧要,但我也想复制它们。 InventoryNbr 有多个重复项。 我只想要不同的库存编号,但我想要 MAX IndexID。 我继续使用它,并获得最低的 IndexID。 如何更改它以获取最大 IndexID?
masterCursor.execute('INSERT INTO MasterV2 SELECT InventoryNbr, IndexListID, col1, col2, col3, col4, col5, col6, Extra FROM Master GROUP BY InventoryNbr ORDER BY IndexListID ASC')
编辑:我的桌子看起来像:
InventoryNbrs | IndexListID
12345 | 123
12345 | 124
12345 | 125
12346 | 126
12346 | 127
12347 | 128
我希望我的新表看起来像:
InventoryNbrs | IndexListID
12345 | 125
12346 | 127
12347 | 128
如果我理解正确,您可以使用 window 函数:
INSERT INTO MasterV2 -- you should list the columns here
SELECT InventoryNbr, IndexListID, col1, col2, col3, col4, col5, col6, Extra
FROM (SELECT m.*,
ROW_NUMBER() OVER (PARTITION BY InventoryNbr ORDER BY IndexListID DESC) as seqnum
FROM Master m
) m
WHERE seqnum = 1;
SELECT
每个InventoryNbr
返回一行。 一行是IndexListID
值最大的行。
用这个:
INSERT INTO MasterV2
SELECT InventoryNbr, MAX(IndexListID), col1, col2, col3, col4, col5, col6, Extra
FROM Master
GROUP BY InventoryNbr
上述 select 语句利用 SQLite 的记录功能为每个InventoryNbr
返回具有最大IndexListID
的行。
您可以在此处找到更多信息: 简单的 Select 处理
你可以使用not exists
如下:
INSERT INTO MasterV2
SELECT t.*
FROM your_table t
Where not exists
(Select 1 from your_table tt
Where tt.InventoryNbr = t.InventoryNbr and tt.IndexListID > t.IndexListID );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.