admin

MySQL在AND,OR子句和查询问题之间进行选择,查询

sql

我有一个item具有两个属性(codename)的表。
现在,我想通过以下方式将它们分组:

group a: code between (5300 and 5310),(7100,7200),(8210,8290)
group b: code not between (5300 and 5310),(7100,7200),(8210,8290)

我如何使用MySQL查询来做到这一点?


阅读 181

收藏
2021-07-01

共1个答案

admin

“群”是什么意思?

如果要使用GROUP BY,可以执行以下操作:

SELECT
    CASE
        WHEN
            code BETWEEN 5300 AND 5310 OR
            code BETWEEN 7100 AND 7200 OR
            code BETWEEN 8210 AND 8290
        THEN 'Group A'
        ELSE 'Group B'
    END AS grp,
    COUNT(*) AS cnt
FROM your_table
GROUP BY grp

也许您只是想订购?

SELECT
    CASE
        WHEN
            code BETWEEN 5300 AND 5310 OR
            code BETWEEN 7100 AND 7200 OR
            code BETWEEN 8210 AND 8290
        THEN 'Group A'
        ELSE 'Group B'
    END AS grp,
    *
FROM your_table
ORDER BY grp

还要注意BETWEEN包括两个端点,这可能不是您的意思。

2021-07-01