I've got a table with a field that is similar to this:
ANIMAL
========
FISH 54
FISH 30
DOG 12
CAT 65
CAT 09
BIRD 10
FISH 31
DOG 10
The field may later have new animals added, such as
GOAT 72
DOG 20
What I'd like to do is make a SELECT
query that returns one unique row per animal name, returning a data set with one row per type of animal, which I can later parse to make a list of animals present in my table.
So, after the magic, I'd have
FISH 54
DOG 12
CAT 65
BIRD 10
GOAT 72
...from which I would make my list.
So far, I've been muddling around with subqueries, SELECT DISTINCT
, and SUBSTRING()
, but I feel that any result I came up with would probably pale in comparison to the might of the SO hive mind. Can someone help?
UPDATE
If it helps, my failed attempt sort of illustrates what I want to do:
SELECT DISTINCT substring(animal,1,4) FROM table;
only now I don't have the whole name, just a substring. :(
This will work for SQL Server. If you use something else you need to figure out the corresponding functions to left and charindex. Left could of course be replaced with a substring.
select distinct left(T.Animal, charindex(' ', T.Animal, 1)-1)
from YourTable as T
Result:
-------------------------
BIRD
CAT
DOG
FISH
In MySQL you would use left and locate. (Code not tested)
select distinct left(T.Animal, locate(' ', T.Animal, 1)-1)
from YourTable as T
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With