I would like to make a SELECT query which group by 3 first varchars ond shows it onces for each. for example the table "tblanimals":
id name age
-- ---- ---
1 DOG1 10
2 DOG2 12
3 DOG3 14
4 CAT1 16
5 CAT2 18
the output should be:
DOG
CAT
after it I need to make another (inside loop) simple query to show the details of each result from the last query we made:
DOG DOG1 10
DOG2 12
DOG3 14
CAT CAT1 16
CAT2 18
10X
This query would help you:
Fiddle : here
select
(
case i.rank
when 1 then i.subname
else '' end
) groupname,
i.name,i.age
from
(SELECT SUBSTRING(`NAME`,1,3)AS SUBNAME, t.name,t.AGE ,
(
CASE SUBSTRING(`NAME`,1,3)
WHEN @curType
THEN @rownum := @rownum + 1
ELSE @rownum := 1 AND @curType := (SUBSTRING(`NAME`,1,3)) END
)+1 AS rank
FROM TEST t,
(SELECT @rownum := 0, @curType := '') r
) i
OUTPUT:
GROUPNAME | NAME | AGE
DOG | DOG1 | 10
| DOG2 | 12
| DOG3 | 14
CAT | CAT1 | 16
| CAT2 | 18
QUERY EXPLANATION
The innerQuery (i) is for Ranking and getting the rownumbers based on the first 3 characters of the animal name. Using case statement to display the animal name only if rownumber=1. A blank character would be displayed if rownumber is anything else other than 1.
You can group this using SUBSTR()
select SUBSTR(name,1,3) as n from test group by n;
Result you want:
select SUBSTR(name,1,3) as n,id,name,age from test;
SELECT SUBSTRING(name,1,3) AS first3Char, name,age FROM test2
GROUP BY first3Char,fName,lName
Please check if above Query would serve your purpose.