Try this:
SELECT c.name
FROM (SELECT c.name, IF(@lastLetter=@lastLetter:=LEFT(c.name, 1), @cnt:=@cnt+1, @cnt:=0) letterCnt
FROM customers c, (SELECT @lastLetter:='', @cnt:=0) A
ORDER BY c.name ASC
) AS c
WHERE c.letterCnt < 5
Question
I have one table customers which has one field 'name' with a to z names records.
I get records from a to z with asc query
SELECT * FROM `customers` ORDER BY name ASC
But how can i get 5 records which starts with all a to z alphabets with only one query?
Output:
a
a
a
a
a
b
b
b
b
b and so on to z. Thanks in advance.
Solution
Try this:
SELECT c.name
FROM (SELECT c.name, IF(@lastLetter=@lastLetter:=LEFT(c.name, 1), @cnt:=@cnt+1, @cnt:=0) letterCnt
FROM customers c, (SELECT @lastLetter:='', @cnt:=0) A
ORDER BY c.name ASC
) AS c
WHERE c.letterCnt < 5
OTHER TIPS
When you use SQL you can use functions like Rank, DENSE_RANK and ROW_NUMBER
DECLARE @Customer AS TABLE
(
Id int,
Name varchar(50)
)
INSERT INTO @Customer VALUES
(1, 'aa'),
(2, 'ab'),
(3, 'ac'),
(4, 'ba'),
(5, 'bb'),
(6, 'bc'),
(7, 'ca'),
(8, 'cb'),
(9, 'cc')
select *
from (
select *,
RANK() OVER(PARTITION BY SUBSTRING(Name, 1, 1) ORDER BY Name ASC) AS [Rank]
from @Customer
) tableWithRank
WHERE tableWithRank.Rank <= 2
Output:
1| aa|1
2| ab|2
4| ba|1
5| bb|2
7| ca|1
8| cb|2