MySql,如何在正或负的选择查询中进行分组?
我想按所有消极的价值观和所有积极的价值观进行分组,有什么想法如何做到这一点?
I would like to group by all the the values which are negative and all those which are positive, any ideas how to do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
GROUP BY SIGN(field) 应该可以。
GROUP BY SIGN(field) should work.
Stefan 的解决方案看起来是迄今为止最好的答案。如果您希望 0 与正数分组,您可以使用
Stefan's solution looks like the best answer so far. If you would prefer for 0 to be grouped in with positive numbers, you can use
尝试这样的事情:
其中 foo 是具有正值或负值的列
编辑:如果您希望将零值与正值和负值区别对待,Stefan 的解决方案会更优雅、更好。
Try something like this:
where foo is the column with the positive or negative values
EDIT: Stefan's solution is more elegant and better if you want zero values treated differently from positive and negative ones.
我知道这个问题很久以前就被问过,但它可能会对将来的某人有所帮助。
注意:下面是在 SQL Server 中测试的,我相信同样的逻辑也适用于 MySql。
I know the question was asked long ago, but it may help someone in the future.
NOTE: Below was tested in SQL server, I believe the same logic will apply in MySql.