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:

  1. a

  2. a

  3. a

  4. a

  5. a

  6. b

  7. b

  8. b

  9. b

  10. b and so on to z. Thanks in advance.

Was it helpful?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top