Aldo,
If you want the row with the smallest DetailID value for each
ElementID, you can do this (untested for typos)
select ElementID, DetailID, Category
from T as T1
where DetailID = (
select min(T2.DetailID) from T as T2
where T2.ElementID = T1.ElementID
)
Steve Kass
Drew University
[quoted text, click to view] Aldo S. wrote:
>Hi,
>
>I have the following details table:
>
>ElementID DetailID Category
>10001 2 1482
>10001 3 1914
>10001 4 1705
>10001 5 1683
>10001 6 2031
>10002 3 1592
>10002 4 2144
>10002 6 1976
>10002 7 1869
>10003...
>.....
>
>Now what I need is an SQL/SP that will allow me to obtain only the first
>record that is
>different in the ElementID field.
>
>Example, I need a result set that will give me:
>
>ElementID DetailID Category
>10001 2 1482
>10002 3 1592
>10003...
>.....
>
>What is the SQL to accomplish it ?
>
>Thanks a lot
>Aldo
>
>
>
>
>
SELECT elementid, detailid, category
FROM YourTable AS T
WHERE detailid =
(SELECT MIN(detailid)
FROM YourTable
WHERE elementid = T.elementid)
--
David Portas
SQL Server MVP
--
Hi,
I have the following details table:
ElementID DetailID Category
10001 2 1482
10001 3 1914
10001 4 1705
10001 5 1683
10001 6 2031
10002 3 1592
10002 4 2144
10002 6 1976
10002 7 1869
10003...
......
Now what I need is an SQL/SP that will allow me to obtain only the first
record that is
different in the ElementID field.
Example, I need a result set that will give me:
ElementID DetailID Category
10001 2 1482
10002 3 1592
10003...
......
What is the SQL to accomplish it ?
Thanks a lot
Aldo
[quoted text, click to view] "Aldo S." <grapher@yahoo.com> wrote in message
news:%233UJoc$4EHA.3380@TK2MSFTNGP09.phx.gbl...
> <CUT>Both queries worked perfectly.
>
Apologies to Zach if I am wrong, but I think his answer will fail if you
ever have a MIN(Category) that is not related to the MIN(DetailID) from that
set... In other words, it only appeared to work because your Categories and
Details happen to have the same sorting order.
David's example should give the correct answer regardless... Now the only
thing to worry about is whether or not you asked the right question. :-)
Cheers!
There is also no guarantee that my solution will provide only one row per
Elementid. Since Aldo didn't tell us the key of his table we don't know if
Detailids can be duplicated.
An alternative solution worth considering is:
SELECT elementid,
MIN(detailid*10000+category)/10000,
MIN(detailid*10000+category)%10000
FROM YourTable
GROUP BY elementid
(assuming the columns are all INTEGER)
--
David Portas
SQL Server MVP
--