| Author |
Topic |
|
Dargon
Starting Member
26 Posts |
Posted - 2008-08-12 : 11:22:30
|
| Hi all,I am trying to display MIN MAX and 'end' values for the same range.Here is data sample:declare @t table(PrdID int,DateIndex int,Qty float)Insert into @t values(1,1,11)Insert into @t values(1,2,22)Insert into @t values(1,3,13)Insert into @t values(1,4,14)Insert into @t values(1,5,20)Insert into @t values(1,6,16)Insert into @t values(1,7,33)Insert into @t values(1,8,18)Insert into @t values(1,9,19)declare @ranges table(StartR int,EndR int)Insert into @ranges values(1,4)Insert into @ranges values(5,10)So I want to have result like this:PrdID StartR EndR MinQty MaxQty EndQty1......1.........4......11.......22.......141..... 5........10......16.......33.......19 The query looks pretty simple, but the problem is that @t table is actually result of multiple joins and calculations and if it takes time to run it. I would like to avoid to join @t multiple times. The @ranges table is small, so I am trying to use it to get all needed number in one shoot. Any Ideas hot to do it? I have feeling that it could be done, but I am stuck.Thanks. |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-08-12 : 11:34:58
|
[code]DECLARE @Products TABLE ( ProdID INT, DateIndex INT, Qty FLOAT )INSERT @ProductsSELECT 1, 1, 11 UNION ALLSELECT 1, 2, 22 UNION ALLSELECT 1, 3, 13 UNION ALLSELECT 1, 4, 14 UNION ALLSELECT 1, 5, 20 UNION ALLSELECT 1, 6, 16 UNION ALLSELECT 1, 7, 33 UNION ALLSELECT 1, 8, 18 UNION ALLSELECT 1, 9, 19DECLARE @Ranges TABLE ( StartR INT, EndR INT )INSERT @RangesSELECT 1, 4 UNION ALLSELECT 5, 10SELECT ProdID, StartR, EndR, MIN(Qty) AS MinQty, MAX(Qty) AS MaxQty, MAX(CASE WHEN RecID = 1 THEN Qty ELSE 0 END) AS EndQtyFROM ( SELECT p.ProdID, r.StartR, r.EndR, p.Qty, ROW_NUMBER() OVER (PARTITION BY p.ProdID, r.StartR ORDER BY p.DateIndex DESC) AS RecID FROM @Ranges AS r INNER JOIN @Products AS p ON p.DateIndex BETWEEN r.StartR AND r.EndR ) AS dGROUP BY ProdID, StartR, EndR[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
Dargon
Starting Member
26 Posts |
Posted - 2008-08-12 : 11:47:25
|
| Oh, interesting... I never used PARTITION BY before. Just wondering what the performance would be. Thanks, I'll give it a try.Dargon |
 |
|
|
|
|
|