Mysql COUNT、GROUP BY 和 ORDER BY
这听起来很简单,但我就是想不出来。
我有一个表orders
(id
、username
、telephone_number
)。
我想通过比较 telephone_number
中的最后 8 个数字来获取一位用户的订单数量。
我尝试使用 SUBSTR(telephone_number, -8),我进行了很多搜索和实验,但仍然无法让它工作。
有什么建议吗?
This sounds quite simple but I just can't figure it out.
I have a table orders
(id
, username
, telephone_number
).
I want to get number of orders from one user by comparing the last 8 numbers in telephone_number
.
I tried using SUBSTR(telephone_number, -8)
, I've searched and experimented a lot, but still I can't get it to work.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
//内存密集型。
或
//相同,但更好更快。
//Memory intensive.
OR
//The same, but better and quicker.
您可以使用以下查询从列值中获取最后 8 个字符。
选择 right(rtrim(First_Name),8) FROM [ated].[dbo].[Employee]
You can use the below query to get last 8 characters from a column values.
select right(rtrim(First_Name),8) FROM [ated].[dbo].[Employee]
未经测试:
想法:
COUNT(*)
(即每个GROUP
中的行数)以及Orders
中的所有字段(>*
)GROUP
按telephone_number
1 的最后八位数字ORDER
号码行中GROUP
按降序排列。1) 如果您计划经常执行此类查询,则可能需要在电话号码的最后部分建立某种索引。如何最好地实现这一点取决于字段中存储的具体值。
Untested:
The idea:
COUNT(*)
(i.e., number of rows in eachGROUP
ing) and all fields fromOrders
(*
)GROUP
by the last eight digits oftelephone_number
1ORDER
by number of rows inGROUP
ing descending.1) If you plan to do this type of query often, some kind of index on the last part of the phone number could be desirable. How this could be best implemented depends on the concrete values stored in the field.