Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
cragi
Starting Member
14 Posts |
Posted - 2006-01-07 : 01:08:53
|
| I'm running MSSQL 2K and have a very complex nested query. In one of the query nests, I want to perform and aggregate query, such that for every Program, I recieve the lowest rate and its corresponding LTV number. I basically want the ProgramID, Rate, and LTV returned.Here is the query, which works but it doesnt provide the corresponding LTV:SELECT MIN(MD2.Rate) AS Expr1, P2.ProgramID FROM MatrixDetails AS MD2 INNER JOIN Matrix AS M2 ON MD2.MatrixID = M2.MatrixID INNER JOIN Programs AS P2 ON M2.MatrixID = P2.MatrixID WHERE MD2.TEST='54' GROUP BY P2.ProgramID6.65 106.65 117.15 127.15 136.49 167.15 176.25 186.25 216.25 236.25 247 257 267.5 27...I want the LTV number as well, so I tried:SELECT MIN(MD2.Rate) AS Expr1, P2.ProgramID, MD2.LTVFROM MatrixDetails AS MD2 INNER JOIN Matrix AS M2 ON MD2.MatrixID = M2.MatrixID INNER JOIN Programs AS P2 ON M2.MatrixID = P2.MatrixIDGROUP BY P2.ProgramID, MD2.LTVORDER BY P2.ProgramID6.65 10 656.85 10 706.9 10 756.95 10 807.05 10 857.5 10 908.25 10 956.65 11 656.85 11 706.9 11 756.95 11 807.05 11 85...Unfortunately it didnt filter down to the lowest since it uses the lowest for every LTV and ProgramID, not just ProgramID |
|
|
cragi
Starting Member
14 Posts |
Posted - 2006-01-07 : 01:13:28
|
| was trying to edit it before posting but it sent.. basically there are a ton of conditions being tested in the where clause and subclauses that I'm excluding to simplify the issue. I would like to retrieve not just the minimum value, but also all of the contents of the record containing that minimum value. If I used a nested query to look up just the minimum value, I would need to retest all of the conditions, which I'm hoping to avoid.... |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2006-01-07 : 06:34:03
|
"was trying to edit it before posting but it sent"On posts that you have Authored there is a little icon to let you re-edit them after posting ... if that helps!This will select the LTV for the "MIN" row in your aggregate. The code in red is to provide a single (I've chosen MIN) value for LTV if Rate + ProgramID is NOT unique in MatrixDetailsSELECT T.Expr1, T.ProgramID, MIN(MD3.LTV)FROM( SELECT MIN(MD2.Rate) AS Expr1, P2.ProgramID FROM MatrixDetails AS MD2 INNER JOIN Matrix AS M2 ON MD2.MatrixID = M2.MatrixID INNER JOIN Programs AS P2 ON M2.MatrixID = P2.MatrixID WHERE MD2.TEST='54' GROUP BY P2.ProgramID) T JOIN MatrixDetails AS MD3 ON MD3.Rate = T.Expr1GROUP BY T.Expr1, T.ProgramID Kristen |
 |
|
|
|
|
|
|
|