【发布时间】:2019-01-26 09:14:36
【问题描述】:
我有一个源表,其中每个产品都有几个不同的价格(取决于订单数量)。这些价格是垂直列出的,因此每个产品可以有不止一行来显示其价格。
例子:
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)
老实说,我不知道如何仅使用 SQL 或 VBA(这些是我能够使用的唯一语言 -> MS-Access)来做到这一点。
【问题讨论】:
标签: sql loops ms-access select subquery