按字母顺序将SQL记录集按字母顺序分组

时间:2012-04-29 15:44:05

标签: mysql grouping alphabetical

通常情况下,我首先要做好功课,但是我现在正面临最后期限,并认为我会把它扔到那里寻求帮助,主要是因为我从以前的经验中知道我认为复杂的任何东西实际上是轻而易举的SQL。

我希望按字母范围对结果进行分组,而不仅仅是单个字母。所以,最终我希望我的输出类似于

ABCD:
-- Alpha
-- Bravo
-- Charlie
-- Delta

EFGH:
-- Echo
-- Foxtrot
-- Gulf
-- Hotel

到目前为止,我一直在使用ORDER BY LOWER(name) ASC然后只是将记录复制到数组结构中以获得单个字母分组(A,B,C等),但这需要扩展到分组字母范围,我想知道它有更快/更有效的方式。

纯SQL解决方案?或者用PHP进行后期处理?

提示,技巧,完整答案一如既往地受到赞赏。

1 个答案:

答案 0 :(得分:0)

这有点难看,但尝试使用这样的UNION:

SELECT * FROM (
    SELECT 'ABCD' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('A','B','C','D')
    UNION
    SELECT 'EFGH' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('E','F','G','H')
    UNION
    SELECT 'IJKL' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('I','J','K','L')
    UNION
    SELECT 'MNOP' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('M','N','O','P')
    UNION
    SELECT 'QRST' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('Q','R','S','T')
    UNION
    SELECT 'UVWX' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('U','V','W','X')
    UNION
    SELECT 'YZ' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('Y','Z')
) AS myResults ORDER BY mygroup,name

向GROUP BY添加一点将为您提供COUNT:

等聚合结果
SELECT myGroup, COUNT(name) as myGroupCount FROM (
    SELECT 'ABCD' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('A','B','C','D')
    UNION
    SELECT 'EFGH' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('E','F','G','H')
    UNION
    SELECT 'IJKL' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('I','J','K','L')
    UNION
    SELECT 'MNOP' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('M','N','O','P')
    UNION
    SELECT 'QRST' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('Q','R','S','T')
    UNION
    SELECT 'UVWX' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('U','V','W','X')
    UNION
    SELECT 'YZ' AS myGroup, name FROM users WHERE LEFT(name,1) IN ('Y','Z')
) AS myResults GROUP BY mygroup ORDER BY mygroup,name