【问题标题】:How to Create a New Table with Distinct Values but selecting the Max from another column如何创建具有不同值的新表但从另一列中选择最大值
【发布时间】:2021-01-16 16:50:07
【问题描述】:

我正在使用 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

【问题讨论】:

  • 请提供样本数据和期望的结果。这真的会澄清你的逻辑。

标签: python sql sqlite


【解决方案1】:

使用这个:

INSERT INTO MasterV2 
SELECT InventoryNbr, MAX(IndexListID), col1, col2, col3, col4, col5, col6, Extra 
FROM Master 
GROUP BY InventoryNbr 

上述 select 语句为每个 InventoryNbr 返回最大 IndexListID 的行,利用了 SQLite 的文档功能。
你可以在这里找到更多:Simple Select Processing

【讨论】:

  • 完美。这非常简单且有效。我相信我之前尝试过 MAX(IndexListID),但最后我没有 Group BY,它只在我的新表中插入了 1 行。
【解决方案2】:

如果我理解正确,你可以使用窗口函数:

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;

SELECTInventoryNbr 返回一行。第一行是IndexListID最大的行。

【讨论】:

    【解决方案3】:

    你可以使用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 );
    

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 2019-05-31
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2022-09-30
      • 1970-01-01
      相关资源
      最近更新 更多