在SQL中对多列进行排序时,如何使空值最后出现?

时间:2019-01-17 15:41:07

标签: sql sql-server sql-order-by

$( ".home .images .image-slide div" ).each(function() {
    var count = $(this).children().length; 
    if (count > 1) {
        $(this).find("img:first-child").addClass("active");
        var self = $(this);
        setInterval(function(){ 
            if(self.find('.active').is(":last-child")){
                self.find('.active').removeClass("active").fadeOut().parent().find("img:first-child").addClass("active").fadeIn();
            } else {
                self.find('img.active').removeClass("active").fadeOut().next().fadeIn().addClass("active");
            }
        }, 4000);
    }
}); 

如何对输出进行排序,以使CREATE TABLE #sorttest (test int, test2 int) INSERT INTO #sorttest VALUES (1, 2), (5, 4), (4, 3), (NULL, 1), (3, NULL), (2, 5) SELECT * FROM #sorttest ORDER BY CASE WHEN test IS NULL THEN 1 ELSE 0 END, test DESC DROP TABLE #sorttest 对于两列都排在最后?

enter image description here

2 个答案:

答案 0 :(得分:1)

DECLARE @sorttest TABLE ( test1 INT, test2 INT)

INSERT INTO @sorttest values
(1,2),(5,4),(4,3),(NULL,1),(3,null),(2,5)

DECLARE @temp1 TABLE ( ID1 INT IDENTITY(1,1) PRIMARY KEY, test3 INT )
DECLARE @temp2 TABLE ( ID2 INT IDENTITY(1,1) PRIMARY KEY, test4 INT )

INSERT INTO @temp1
SELECT test1 FROM @sorttest ORDER BY test1 DESC

INSERT INTO @temp2
SELECT test2 FROM @sorttest ORDER BY test2 DESC

SELECT test3, test4 FROM @temp1 t1
LEFT JOIN @temp2 t2 ON t1.ID1 = t2.ID2

我使用了另外两个临时表来操纵数据,以使用join语句获得所需的输出。

如果需要在一行中重新排列值,则比单个select语句需要更多的逻辑。

输出:

test3   test4
5       5
4       4
3       3
2       2
1       1
NULL    NULL

答案 1 :(得分:0)

您可以这样做

SELECT * FROM #sorttest ORDER BY
CASE WHEN test IS NULL and test2 is null THEN 2 ELSE 
   case when test is null or test2 is null then 1 end 
   END ,test desc

但是非null列的顺序有点奇怪