Home All Groups Group Topic Archive Search About

select statement question

Author
8 Sep 2005 5:52 PM
jason
suppose i've got a table like so:

create table foo (
  foo_name varchar(50) not null primary key nonclustered,
  foo_age int not null,
  foo_zipcode varchar(20) null
)
go

and you populate it with some data like so:

insert into foo (foo_name, foo_age, foo_zipcode)
values ('john', 31, '10101')
insert into foo (foo_name, foo_age, foo_zipcode)
values ('jane', 31, null)
insert into foo (foo_name, foo_age, foo_zipcode)
values ('jema', 31, '01010')
insert into foo (foo_name, foo_age, foo_zipcode)
values ('jack', 30, '10101')
insert into foo (foo_name, foo_age, foo_zipcode)
values ('jill', 30, '10101')
insert into foo (foo_name, foo_age, foo_zipcode)
values ('jeff', 30, null)
go

the select statement i'm looking for is kind of like this:

select foo_name from foo
where foo_zipcode is not null

except that i only want to return one member per age value. it doesn't
actually matter which row i return for each category. it could be based
of name alphabetically, or just the first row encountered, doesn't
really matter. the key is that i want only one row per age value where
foo_zipcode is not null. sample return values i'm looking for could be
like so:

foo_name
--------
john
jack

thanks in advance for any help!

jason

Author
8 Sep 2005 6:00 PM
David Portas
SELECT MIN(foo_name)
FROM foo
WHERE foo_zipcode IS NOT NULL
GROUP BY foo_age ;

--
David Portas
SQL Server MVP
--
Author
8 Sep 2005 6:20 PM
jason
worked perfectly, thanks a lot. i really need to improve my grasp of
the group by and having clauses, they keep coming up in queries that
stump me :)
Author
8 Sep 2005 8:12 PM
Uday
Smart idea.....!!  I'll use it too...
_Uday

AddThis Social Bookmark Button