I have Two tables FactLik
(2 million rows) and UpdateStPrice
( 500k rows).
I need to update FactLik
table using rules.
UpdateStPrice
| PRODUCTKEY | WAREHOUSEKEY | STARTDATE | ENDDATE | PRIORITY | UNITPRICE |
---------------------------------------------------------------------------
| 36975 | 6 | 20120630 | 20121011 | 0 | 395 |
| 36975 | 6 | 20121018 | 20291231 | 0 | 371 |
| 36975 | 6 | 20121126 | 20121211 | 120 | 313 |
| 36975 | 6 | 20121126 | 20121219 | 120 | 288 |
| 36975 | 6 | 20121212 | 20291231 | 120 | 313 |
FactLik
| TIMEKEY | PRODUCTKEY | PRODUCTGROUPKEY | WAREHOUSEKEY | PRICE |
-------------------------------------------------------------------
| 20121205 | 36975 | 89 | 6 | (null) |
Rules for updating FactLik row
- For same
ProductKey
,WarehouseKey
find inUpdateStPrice
row wherePriority
is MAX andFactLik.TimeKey
is betweenStartDate
andEndDate
. - Now find row where
StartDate
is MAX. - Now find row where
EndDate
is MIN.
ExpectedResult from UpdateStPrice
:
| PRODUCTKEY | WAREHOUSEKEY | STARTDATE | ENDDATE | PRIORITY | UNITPRICE |
---------------------------------------------------------------------------
| 36975 | 6 | 20121126 | 20121211 | 120 | 313 |
Result FactLik
:
| TIMEKEY | PRODUCTKEY | PRODUCTGROUPKEY | WAREHOUSEKEY | PRICE |
-------------------------------------------------------------------
| 20121205 | 36975 | 89 | 6 | 313 |
I have My QUERY which is very slow, actually she running to slow more than 12 hours. I have some Indexes on both tables (Execution plan suggested) but they don' help at all:)
So If you can help me to optimize this query I'll be very grateful.