July 7, 2005 at 7:34 am
for queries that do an aggregate and lots of joins, what's a better idiom:
1. wrap joined/selected columns in a min()
2. add joined/selected columsn to the group by
3. isloate the aggregation in a subquery and join to that.
EXAMPLE OF 1.:
select
min(S.BizSubBusinessUnitName) as BizSubBusinessUnitName,
min(BU.BizBusinessUnitName) as BizBusinessUnitName,
D.BizStrategyName,
I.SevernTicker,
min(I.SecurityName) as SecurityName,
min(I.CommonTicker) as CommonTicker,
min(IT.InstID) as InstID,
sum(P.Quantity) as SRTradeQuantity,
...
from
(select * from dbo.fnPositionMarkS(null)) P
join tbInstTranche IT WITH (NOLOCK) on IT.InstTrancheID = P.InstTrancheID
join tbBizStrategy D WITH (NOLOCK) on D.BizStrategyID = P.BizStrategyID
...
group by
D.BizStrategyName, I.SevernTicker
July 7, 2005 at 8:21 am
Do you have a specific case?
This is one of those "it always depends" .
July 7, 2005 at 8:27 am
no specific case in mind other than the abbreviated code I already posted.
Can you give an example of why you'd choose any one idiom over the other 2?
July 7, 2005 at 8:29 am
Frankly no... I usually try to find the fasted query for a situation... and often 2 versions can have the same performance. Maybe someone else might think of one.
July 8, 2005 at 1:14 am
Just be aware that when you do a MIN or MAX on two columns from the same table, you are probably NOT getting the values from the same row.
Sometimes I find that the best technique is to use a subquery for the aggregates, and joining that subquery using the GROUP BY columns to the outer table so I can see the same City, State, and Zip per table row as an example.
SELECT Customer.Name, Customer.City, Customer.State, Customer.Zip, Q.Payments
FROM Customer
INNER JOIN (SELECT SUM(Payment) AS Payments
FROM Customer
GROUP BY SSN) AS Q
ON Customer.SSN = Q.SSN
If you want a better example of your needs, provide a starting place, sample data, and expected output...
Andy
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply