2012-09-30 37 views
0

我有一個顯示結果列表的SQL查詢。我的數據庫中的每一行都有大約20列,並不是每列都是強制性的。我希望SQL查詢的結果是 按填充列的數量排序。頂部空列最少的行,底部空列最多的行。你們有沒有想法如何做到這一點?SQL:按空列數排序

我想過在表格中增加一個額外的列,如果每次用戶編輯他們的行時都更新,這個數字將表示空列的數量,我可以用我的列表排序。然而,這聽起來像不必要的麻煩,但也許沒有其他辦法?我敢肯定這裏有人會知道!

感謝,

桑德

回答

3

你可以在幾乎任何有大型病例陳述的數據庫中做到這一點:

order by ((case when col1 is not null then 1 else 0 end) + 
      (case when col2 is not null then 1 else 0 end) + 
      . . . 
      (case when col20 is not null then 1 else 0 end) 
     ) desc 
+0

兩個頭腦,一個雖然:Andomar認爲同樣的事情,它的工作!非常感謝! – user1555076

2

您可以通過空列的量訂購:

order by 
     case when col1 is null then 1 else 0 end + 
     case when col2 is null then 1 else 0 end + 
     case when col3 is null then 1 else 0 end + 
     ... 
     case when col20 is null then 1 else 0 end 

(注意+在行的結尾:它與整數只有一個列空行數,按升序排序)。

+0

兩個頭腦,一個雖然:戈登認爲同樣的事情,它的工作!非常感謝! – user1555076