mysql group语句可以排序_MySQL group_concat()按case语句值排序

bd96500e110b49cbb3cd949968f18be7.png

In a MySQL group_concat() clause, I'm trying to order the resulting values of a case statement. The following query configuration properly orders things.name but does not order the 'Non-US' or 'Unknown' values within the same context.

SELECT

things.id

,group_concat(DISTINCT

CASE

WHEN things.name <> 'United States' THEN 'Non-US'

WHEN things.name IS NULL THEN 'Unknown'

ELSE things.name

END

ORDER BY name SEPARATOR ', ')

FROM things

GROUP BY things.id

I want to do something like this, but it's not working:

SELECT

things.id

,group_concat(DISTINCT

(CASE

WHEN things.name <> 'United States' THEN 'Non-US'

WHEN things.name IS NULL THEN 'Unknown'

ELSE things.name

END) AS new_name

ORDER BY new_name SEPARATOR ', ')

FROM things

GROUP BY things.id

Is there a way to sort by "new_name" without using sub-queries/ nested queries?

解决方案

You can accomplish this by ordering by column position instead of column name.

For your case ORDER BY 1 should work.

SELECT

things.id

,group_concat(DISTINCT

CASE

WHEN things.name <> 'United States' THEN 'Non-US'

WHEN things.name IS NULL THEN 'Unknown'

ELSE things.name

END

ORDER BY 1 SEPARATOR ', ')

FROM things

GROUP BY things.id

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值