I've got a list of customers, customer names, ... from another db (I didn't
design it).
I want to get a list of all of the customers plus the first customer name.
So if customer 1 appears twice (customer name = 'Fred' and 'John') I want
the first one it finds.
Is there an easy way to do this without spinning through all of the records.
I'm using the results of the query as a select statement as input to an
insert statement.
TIA - Jeff.
Aaron Bertrand [SQL Server MVP] - 22 Jul 2008 18:24 GMT
SQL Server doesn't understand the concept of "first" since a table is an
unordered set of rows. Do you have some other column that can be used to
break this tie? e.g. is there a created_date column or something? If so,
you could say:
SELECT
customer_id,
customer_name
FROM
customers c
INNER JOIN
(
SELECT customer_id,
created_date = MIN(created_date) -- or MAX?
FROM customers
GROUP BY customer_id
) s
ON c.customer_id = s.customer_id
AND c.created_date = s.created_date;
I suppose this could still yield ties of you have multiple rows for the same
customer with the same created_date. Hard to suggest anything further
without more details.
> I've got a list of customers, customer names, ... from another db (I
> didn't design it).
[quoted text clipped - 8 lines]
>
> TIA - Jeff.
Steve Kass - 22 Jul 2008 19:11 GMT
Mufasa,
In SQL Server 2005, it's not hard:
with T as (
select
*,
row_number() over (
partition by your_unique_key
order by their_unique_key
) as occurence
from theTable
)
select <columns you want>
from T
where occurence = 1
This selects the first occurrence in their-key order of
each customer (as defined by your-key).
Steve Kass
Drew University
http://www.stevekass.com
>I've got a list of customers, customer names, ... from another db (I didn't
>design it).
[quoted text clipped - 10 lines]
>
>