Attempting to order table multiple times

半世苍凉 提交于 2019-12-02 23:45:28

问题


I am trying to group multiple rows and order it by the total values but im struggling to figure out whats going wrong.

Name       Total
=======    =======
ASOS        222
Tesco       11
ASOS        11111
Tesco       123

The table should look like this

Name       Total
=======    =======
ASOS        11111
ASOS        222
Tesco       123
Tesco       11

I thought this query would work

select * from tablename order by name asc, total asc

But that shows a result in the wrong order.

Any help would be appreciated.


回答1:


Try this

select * from tablename order by total desc

Selecting two things to ORDER BY doesn't work too well if you're not familiar with ORDER BY syntax. from your description, it looks like you just want the highest total at the top. This query will order the results by total descending (highest first)

if you want the names to be ascending (lowest first) at the same time, try

select * from tablename order by name asc, total desc



回答2:


First order by the max total for each name, descending, the order by total descending:

select *
from tablename t1
order by (select max(total) from tablename t2
          where t1.name = t2.name) desc,
         total desc



回答3:


Try this:

SELECT *
FROM tablename
ORDER BY
    Name,
    char_length(CAST(Total As varchar(max))) DESC,
    Total DESC


来源:https://stackoverflow.com/questions/28992582/attempting-to-order-table-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!