I have table with storage. There is 20 columns for "amount" which can be zero or greater (can not be null).
IDCity | Amount0 | Amount1 | ... Amount19
---------------------------------------------------
ABC | 25 | 7 | ...
... ... ... ...
XYZ | 10 | 6 | ...
And table for consumption & production. There is 20 columns for input "amount" a 20 columns for "output" amount. The "OrderNumber" column has values from 1 to "N". The values are continuous.
IDCity | OrderNumber | InAmount0 | InAmount1 | OutAmount0 | OutAmount1 | ...
----------------------------------------------------------------------------
ABC | 1 | 0 | 0 | 10 | 0 | ...
ABC | 2 | 30 | 0 | 0 | 16 | ...
ABC | 3 | 0 | 14 | 7 | 0 | ...
...
XYZ | 1 | 0 | 9 | 21 | 0 | ...
XYZ | 2 | 9 | 0 | 0 | 19 | ...
XYZ | 3 | 2 | 0 | 0 | 4 | ...
...
I need iterate the rows in "consumption & production" and update the amounts in storage in every city. I开发者_JAVA技巧 want decrease values by "InAmount" columns and increment values by "OutAmount" columns.
However if InAmount1 < Amount1 OR InAmount2 < Amount2 OR ...
the row must be ignored.
The results from sample should be:
IDCity | Amount0 | Amount1 | ... Amount19
---------------------------------------------------
ABC | 12 | 9 | ...
... ... ... ...
XYZ | 1 | 25 | ...
The row "XYZ - 1" is ignored because InAmount1 = 9
AND Amount1 = 6
=> input is greater than storage.
The row "XYZ - 3" is ignored because InAmount0 = 2
AND Amount0 = 10 - 9 = 1
=> input is greater than storage.
I need results fast, but I can allocate a lot of memory. The average row count will be ~10K in storage table and ~25K in consumption&production table.
I guess the CTE will be the right solution, but I didn't be able do it right.
EDIT: The source data can be available in key-value form:
Storage table:
IDCity | Kind | Amount
ABC | 0 | 25
ABC | 1 | 7
...
XYZ | 0 | 10
XYZ | 1 | 6
Consumption & production table:
IDCity | OrderNumber | InKind1 | InAmount1 | InKind2 | InAmount2 | OutKind | OutAmount
ABC | 1 | NULL | NULL | NULL | NULL | 0 | 10
ABC | 2 | 0 | 30 | NULL | NULL | 1 | 16
ABC | 3 | 1 | 14 | NULL | NULL | 0 | 7
...
精彩评论