编写排序查询

时间:2012-05-29 04:18:40

标签: sql sql-server tsql

我有一张表格如下:

Job    Quantity Status
-----------------------
1      100      OK
2      400      HOLD
3      200      HOLD
4      450      OK
5      300     
6      500      

我希望我的结果显示如下:

Job  Quantity Status
----------------------
4      450      OK
2      400      HOLD
1      100      OK
3      200      HOLD
6      500 
5      300

我创建了这个查询,但是当表包含status列为空/空的数据

时,它不起作用
SELECT 
    Job, 
    Quantity, 
    Status 
FROM 
    myTable
ORDER BY CASE 
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 2 
    WHEN QUANTITY <  400 AND STATUS = 'OK' THEN 3 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 4 
    WHEN QUANTITY >= 400 AND STATUS = '' THEN 5 
    WHEN QUANTITY <  400 AND STATUS = '' THEN 6 
END

2 个答案:

答案 0 :(得分:6)

除非我误读,否则我觉得你已经回答了自己的问题。您需要考虑数据何时为NULL

重要的是NULL''的类型不同。就像'' = 0是假的一样,NULL = ''也是如此。 NULL用于表示空值。根据布尔值而不是字符串来考虑它。显然,有时某些事情既不是真的也不是假的,这就是像NULL这样的值会出现的地方。同样,如果你认为字符串是纯数据而不是字符和单词那么空之间就有区别价值,没有任何价值。

有关详细信息,请参阅http://www.w3schools.com/sql/sql_null_values.asp

所以我认为你的代码应该是这样的:

SELECT Job, Quantity, Status 
    FROM myTable
ORDER BY CASE 
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD'  THEN 2 
    WHEN QUANTITY < 400 AND STATUS = 'OK'  THEN 3 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD'  THEN 4 
    WHEN QUANTITY >= 400 AND (STATUS = '' OR STATUS IS NULL)  THEN 5 
    WHEN QUANTITY < 400 AND (STATUS = '' OR STATUS IS NULL)  THEN 6
END

除非您明确将状态设置为'',否则您可能只能使用STATUS IS NULL

答案 1 :(得分:3)

尝试使用以下查询: -

SELECT  
    Job,  
    Quantity,  
    Status  
FROM  
    myTable 
ORDER BY CASE  
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1  
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 2  
    WHEN QUANTITY <  400 AND STATUS = 'OK' THEN 3  
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 4  
    WHEN QUANTITY >= 400 AND COALESCE(STATUS,'') = '' THEN 5  
    WHEN QUANTITY <  400 AND COALESCE(STATUS,'') = '' THEN 6  
END 

COALESCE()函数返回第一个非null参数,因此如果STATUSNULL,它将返回''

http://www.sqlbook.com/SQL/SQL-Coalesce-28.aspx