1

我有一个关于订购我的 SQL 表的问题。我已经尝试了几件事,但找不到我想要的解决方案。

我的表如下所示:

username  childs+pets  childs    pets
=======================================
Max       1                      1
Nico      3            1         2       
Lewis     2            2        
Daniel    2            1         1

我想按 childs+pets (ASCending) 排序我的表,但我想将带有空字段的记录 (Max 和 Lewis) 放在表的底部。结果是:

username  childs+pets  childs    pets
=======================================
Nico      3            1         2
Daniel    2            1         1       
Lewis     2            2        
Max       1                      1

谁能帮我?

4

3 回答 3

1

这是适用于 SQL Server 的解决方案。我还假设 Childs+Pets 是来自两个单独字段的计算字段。

测试数据;

CREATE TABLE #TestData (Username nvarchar(10), Childs int, Pets int)
INSERT INTO #TestData (Username, Childs, Pets)
VALUES
('Max',NULL,1)
,('Nico', 1,2)
,('Lewis',2,NULL)
,('Daniel',1,1)

询问

SELECT
    td.Username
    ,COALESCE(td.Childs,0) + COALESCE(td.Pets,0) Childs_Pets --The coalesce returns a Zero if the field contains a NULL
    ,td.Childs
    ,td.Pets
FROM #TestData td
ORDER BY CASE WHEN td.Childs IS NULL OR td.Pets IS NULL THEN 0 ELSE 1 END DESC
,COALESCE(td.Childs,0) + COALESCE(td.Pets,0) ASC

输出

Username    Childs_Pets     Childs      Pets
Daniel      2               1           1
Nico        3               1           2
Max         1               NULL        1
Lewis       2               2           NULL

CASE语句首先被排序,因此如果其中任何一个都具有 NULL 值,Childs那么Pets它将被推到底部。的排序在你想要的Childs_Pets之后进行排序。ASC

于 2016-11-15T09:35:38.273 回答
0

样本不够清晰,所以选择两者之一:

select      *

from        t

order by    "childs+pets" + 0  desc
           ,case when childs = '' then 2 else 1 end
           ,case when pets   = '' then 2 else 1 end
;          

select      *

from        t

order by    case when childs = '' then 2 else 1 end
           ,case when pets   = '' then 2 else 1 end
           ,"childs+pets" + 0 desc
;        
于 2016-11-15T09:27:52.657 回答
0

最简单的解决方案(适用于 Null 值)只是:

select * 
from mytable
order by coalesce(childs+pets, 9999)

或者,正如您所说,您的空值是零字符串,您也可以使用:

select * 
from mytable
order by case when childs = '' or pets = '' then '9999' else childs+pets end
于 2016-11-15T09:30:03.360 回答