cheryl9063
asked on
TSQL Best practice No loop
I have a table that has the fields: sCustID and severl other fields.. I want to "Group" together the like sCustid's by giving them a unique GroupID number.. If you run my code you will see what I'm trying to do.. The only problem is my code is backwards.. It groups the ones that are no alike together and the ones that are alike have different group numbers.. What am I doing wrong?
DECLARE @tmp TABLE (id TINYINT IDENTITY(1,1), sCustID CHAR(10))
INSERT @tmp
SELECT sCustID FROM ctsapp.app.tblVRUInvReq
SELECT
o.sCustID, o.id - omin.minid + 1 AS GroupNum
FROM @tmp o
INNER JOIN
(SELECT sCustID, MIN(id) minid FROM @tmp GROUP BY sCustID) AS omin ON
o.sCustID = omin.sCustID
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I don't know what I was doing either but thanks!!
Hmmm, have you tried my suggestion?
ASKER
Although I'm sure your answer is fine I don't want to use your suggestion..Based on many reasons I need to use the query I was using.. My question was what was wrong with my code not how do you perform the same thing using different approaches.. Also, my DBA does not want more functions at this time but many many thanks for your response.
>>I don't want to use your suggestion..Based on many reasons I need to use the query I was using.. My question was what was wrong with my code not how do you perform the same thing using different approaches.. <<
your current approach is very clunky. There's no need to create a new temporary table and then select assign group id.the way you're doing
>>Also, my DBA does not want more functions at this time but many many thanks for your response. <<
You don't have to create any function here. Dense_rank is a function that comes with SQL server, same as MIN, MAX, etc.
If you still insist, it's up to you, all I'm saying that at least you should have tried my suggestion and split the points accordingly since I have provided you a valid solution, waaaay simpler than the one you currently have.
your current approach is very clunky. There's no need to create a new temporary table and then select assign group id.the way you're doing
>>Also, my DBA does not want more functions at this time but many many thanks for your response. <<
You don't have to create any function here. Dense_rank is a function that comes with SQL server, same as MIN, MAX, etc.
If you still insist, it's up to you, all I'm saying that at least you should have tried my suggestion and split the points accordingly since I have provided you a valid solution, waaaay simpler than the one you currently have.
ASKER
If you run an execution plan and see what the Optimzer prefers
Query 1 ( my way) cost 21%
Query 2( your way) cost 56%
Any kind of function results in a productivity impact.
Query 1 ( my way) cost 21%
Query 2( your way) cost 56%
Any kind of function results in a productivity impact.
Open in new window