views:

53

answers:

3

I have a table that I need to normalize with many fields In SQL-Server 2000. It contains 2 fields which I'm using to come up with distinct combination as defined by the specs. ID and Rate: there are multiple rows of same IDs and Rates

I first created a temp table by grouping the IDs and Rates combination.

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

Now I use Distinct to find only the unique combinations. So i'll have multiple ID groups sharing same Total and IDCounts

SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp

Now my question is how to join a single ID back to that distinct grouping of IDCounts and Total and put that into a new table? It doesn't matter which one of the IDs in the groups as long as I use one from the same grouping.

+1  A: 

Keeping your temp tables (although this could all be done in a single query):

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

SELECT Total, IDCounts, MIN(ID) AS SomeID
INTO #uniques
FROM #Temp
GROUP BY Total, IDCounts
Cade Roux
Thanks again Cade!
stevenjmyu
+2  A: 

Add "Min(ID) AS FirstID" to the select into #uniques.

SteveCav
A: 

Try something like this:

SELECT MAX(ID) AS Id, Count(*) AS IDCounts, SUM(RATE) As Total 
FROM SOMETABLE
GROUP BY IDCounts, Total
xagyg