[英]SQL: sort by number of empty columns
我有一個顯示結果列表的SQL查詢。 數據庫中的每一行都有大約20列,但並非每一列都是必需的。 我希望按填充列數對SQL查詢的結果進行排序。 空列最少的行在頂部,空列最多的行在底部。 你們中有人有一個如何做的主意嗎?
我考慮過要在表中添加一個額外的列,如果用戶每次編輯其行時都進行了更新,則該數字將指示空列的數量,我可以以此對列表進行排序。 但是,這聽起來像是不必要的麻煩,但是也許沒有其他方法了嗎? 我敢肯定這里的人會知道的!
謝謝,
桑德
您可以在帶有巨大case語句的幾乎所有數據庫中執行此操作:
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
您可以按空列的數量進行排序:
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
(請注意,在行的最后加上+
:這只是一列,其中空字段是整數,以升序排列。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.