How to order by 2 columns combining COALESCE?

蓝咒 提交于 2020-01-26 04:22:24

问题


I have a question about ordering a SQL table. And I can't find a solution on stack or google. My table "Score" seems as follows:

Name    Total   Tries  Game1  Game2  Game3
------------------------------------------
Sam     65      61     10     31     24             
Tom             55     11            30
Jim     65      58     9      34     22 
Dan     62      52     10     30     22

Note: "Total" column is COUNT(Game1 + Game2 + Game3).

As you can see the Total record of Tom is empty, because Tom didn't play Game2.

I want to order my table as follows (highest-lowest priority):

  1. Empty cells (at the bottom of the table)
  2. Total (ASC)
  3. Tries (ASC)

So my table has to look like:

Name    Total   Tries  Game1  Game2  Game3
------------------------------------------
Dan     62      52     10     30     22
Jim     65      58     9      34     22 
Sam     65      61     10     31     24             
Tom             55     11            30

Which SQL query do I have to use?

This is what I have on this moment, but it will not sort on "Tries":

SELECT name, Game1+Game2+Game3 AS Total, Game1, Game2, Game3, Tries
FROM Score 
ORDER BY CASE WHEN Tries or Game1 or Game2 or Game3 IS NULL THEN 0 ELSE 1 END DESC, 
         COALESCE(Game1,0) + COALESCE(Game2,1) + COALESCE(Game3,2) ASC

回答1:


Considering you have NULL instead of empty in Total based on the CASE statement in your order by. Try this Order by

ORDER BY COALESCE(Total,99999999999) ASC,Tries ASC

99999999999 will make the NULL values to sort at the end and the other records will be ordered in ascending order

or

ORDER BY case when Total is null then 0 else 1 end desc,Total ASC,Tries ASC


来源:https://stackoverflow.com/questions/40950146/how-to-order-by-2-columns-combining-coalesce

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