我有一个item具有两个属性(code和name)的表。 现在,我想通过以下方式将它们分组:
item
code
name
group a: code between (5300 and 5310),(7100,7200),(8210,8290) group b: code not between (5300 and 5310),(7100,7200),(8210,8290)
我如何使用MySQL查询来做到这一点?
“群”是什么意思?
如果要使用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包括两个端点,这可能不是您的意思。