SQL排序问题
今日在群中有人提到这样一个SQL排序问题,特贴出与大家一同分享。题目如下,
/*如何实现这样排序1 2 3 4 5 ++....N+1 0 0 0 ...就是0全排后面*/
CREATE DATABASE dbExamples
GO
USE dbExamples;
GO
CREATE TABLE tbExamples (colA INT);
GO
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (1);
INSERT INTO tbExamples (colA) VALUES (2);
INSERT INTO tbExamples (colA) VALUES (3);
INSERT INTO tbExamples (colA) VALUES (NULL);
GO
/*方法一*/
SELECT * FROM tbExamples WHERE colA <> 0
UNION ALL
SELECT * FROM tbExamples WHERE colA = 0
/*方法二*/
SELECT * FROM tbExamples
WHERE colA IS NOT NULL
ORDER BY CASE WHEN colA = 0 THEN 5*10^9 ELSE colA END
欢迎指证。
/*如何实现这样排序1 2 3 4 5 ++....N+1 0 0 0 ...就是0全排后面*/
CREATE DATABASE dbExamples
GO
USE dbExamples;
GO
CREATE TABLE tbExamples (colA INT);
GO
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (0);
INSERT INTO tbExamples (colA) VALUES (1);
INSERT INTO tbExamples (colA) VALUES (2);
INSERT INTO tbExamples (colA) VALUES (3);
INSERT INTO tbExamples (colA) VALUES (NULL);
GO
/*方法一*/
SELECT * FROM tbExamples WHERE colA <> 0
UNION ALL
SELECT * FROM tbExamples WHERE colA = 0
/*方法二*/
SELECT * FROM tbExamples
WHERE colA IS NOT NULL
ORDER BY CASE WHEN colA = 0 THEN 5*10^9 ELSE colA END
欢迎指证。