DECLARE @Table1 TABLE (ID INT IDENTITY(1,1), Field1 INT, FieldSomethingElse VARCHAR(10))
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (1, 'b')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (2, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (765, 'a')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'd')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'f')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (76, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (3, 'r')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (40, 'b')
declare @flag bit = 0;
SELECT *
FROM @Table1
ORDER BY
case when @flag = 1 then ISNULL(Field1,0) else 0 end desc , ID desc
SELECT *
FROM @Table1
ORDER BY
case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
如果我写
1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc
或
2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
建议我使用选项1,但对我来说这两个选项是相同的,因为我看到的结果相同。有什么区别吗?
1和2选项如何影响排序?
答案 0 :(得分:2)
对于第一个子句:
1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc , ID desc
当@flag不等于1时,您将返回0。 对于第二个:
2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
当@flag不等于1时,将返回null
。
因为它位于您的order by
中,所以功能上不会有任何区别。
答案 1 :(得分:0)
我猜有一点区别。当flag = 0时,以下表达式相同
order by case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
和
order by case when @flag = 1 then ISNULL(Field1,0) else null end desc, ID desc
让我们假设我们对两位列进行排序,而不是 Field1 和 Id 。在这种情况下,当对两列进行排序时,将考虑使用NULL。
https://rextester.com/SBDJQ20053
这就是为什么建议使用
case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc
避免排序为空