SQL中的Alpha数字字符串订购
我正在处理一个看起来像这样的查询:
SELECT
CASE
WHEN num BETWEEN 1 AND 5 THEN '1-5'
WHEN num BETWEEN 6 AND 10 THEN '6-10'
WHEN num BETWEEN 11 AND 20 THEN '11-20'
WHEN num > 20 THEN '20+'
END AS bucket,
COUNT(1)
FROM data
GROUP BY 1
...
我想按不同的桶值订购结果,因此结果看起来像该
水桶 | 计数(1) |
---|---|
1-5 | 10 |
6-10 | 11 |
11-20 | 17 |
20+ | 8 |
由于存储桶是一个字符串,因此只需按该列排序就无法解决问题。
SQL中是否有任何字符串操作可以帮助我?出于原因,我不会进入案例陈述是最简单的方法,使我以所需的格式获得结果,因此我宁愿处理一堆字符串操作,而不是按照我想要的顺序进行操作查询
I'm working with a query that looks like this:
SELECT
CASE
WHEN num BETWEEN 1 AND 5 THEN '1-5'
WHEN num BETWEEN 6 AND 10 THEN '6-10'
WHEN num BETWEEN 11 AND 20 THEN '11-20'
WHEN num > 20 THEN '20+'
END AS bucket,
COUNT(1)
FROM data
GROUP BY 1
...
I'd like to order the results by the different values of bucket so the results look something like this
bucket | count(1) |
---|---|
1-5 | 10 |
6-10 | 11 |
11-20 | 17 |
20+ | 8 |
Since bucket is a string, simply sorting by that column doesn't do the trick.
Are there any string operations in SQL that can help me? For reasons I won't get into the CASE statements are the easiest way for me to get results in the format I need, so I'd rather deal with a bunch of string operations to get it in the order I want than change the structure of the query
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的方法使用桶的整数下限(因为整数比字符串更好),并且仅在末尾生成字符串存储桶名称, 分组后。
My approach uses integer lower-bounds for the buckets (as integers are nicer to deal with than strings), and only generates the string bucket names at the very end, after grouping.