Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select distinct substring where like muddleup howto

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. :(

like image 717
Ben Avatar asked Jun 10 '11 04:06

Ben


1 Answers

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
like image 144
Mikael Eriksson Avatar answered Sep 20 '22 20:09

Mikael Eriksson