代码之家  ›  专栏  ›  技术社区  ›  fmedv

循环一个表,再选择另一个表并用SQL/VBA更新第一个表的值

  •  0
  • fmedv  · 技术社区  · 6 年前

    我有一个源表,每个产品有几个不同的价格(取决于订单数量)。这些价格是垂直列出的,因此每个产品可以有多行显示其价格。

    例子:

    ID  | Quantity | Price
    --------------------------
    001 |    5     | 100
    001 |    15    | 90
    001 |    50    | 80
    002 |    10    | 20
    002 |    20    | 15
    002 |    30    | 10
    002 |    40    | 5
    

    我拥有的另一个表是结果表,其中每个产品只有一行,但是有五列,每列可以包含源表每行的数量和价格。

    例子:

    ID  | Quantity_1 | Price_1  | Quantity_2 | Price_2  | Quantity_3 | Price_3  | Quantity_4 | Price_4 | Quantity_5 | Price_5
    ---------------------------------------------------------------------------------------------------------------------------
    001 |            |          |            |          |            |          |            |         |            |
    002 |            |          |            |          |            |          |            |         |            |
    

    结果:

    ID  | Quantity_1 | Price_1  | Quantity_2 | Price_2  | Quantity_3 | Price_3  | Quantity_4 | Price_4 | Quantity_5 | Price_5
    ---------------------------------------------------------------------------------------------------------------------------
    001 |     5      |    100   |     15     |    90    |     50     |    80    |            |         |            |
    002 |     10     |    20    |     20     |    15    |     30     |    10    |     40     |    5    |            |
    

    这是我的Python/SQL解决方案(我完全知道这不可能以任何方式工作,但这是我向您展示我对这个问题的解决方案的解释的唯一方法):

    For Each result_ID In result_table.ID:
        Subselect = (SELECT * FROM source_table WHERE source_table.ID = result_ID ORDER BY source_table.Quantity) # the Subselect should only contain rows where the IDs are the same
    
        For n in Range(0, len(Subselect)): # n (index) should start from 0 to last row - 1
            price_column_name = 'Price_' & (n + 1)
            quantity_column_name = 'Quantity_' & (n + 1)
    
            (UPDATE result_table 
            SET result_table.price_column_name = Subselect[n].Price, # this should be the price of the n-th row in Subselect
                result_table.quantity_column_name = Subselect[n].Quantity # this should be the quantity of the n-th row in Subselect
            WHERE result_table.ID = Subselect[n].ID)
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    这是MS访问中的一个难题。如果可以枚举值,则可以对其进行透视。

    如果我们假设价格是唯一的(或数量或两者),那么您可以生成这样一列:

    select id,
           max(iif(seqnum = 1, quantity, null)) as quantity_1,
           max(iif(seqnum = 1, price, null)) as price_1,
           . . . 
    from (select st.*,
                 (select count(*)
                  from source_table st2
                  where st2.id = st.id and st2.price >= st.price
                 ) as seqnum
          from source_table st
         ) st
    group by id;
    

    我应该注意到,另一个解决方案将使用Python中的数据帧。如果你想走那条路,就问 另一个 用适当的Python标记来提问和标记它。这个问题显然是一个SQL问题。