简体   繁体   English

SQL:按空列数排序

[英]SQL: sort by number of empty columns

I have a SQL query which displays a list of results. 我有一个显示结果列表的SQL查询。 Every row in my database has about 20 columns and not every column is mandatory. 数据库中的每一行都有大约20列,但并非每一列都是必需的。 I would like the result of the SQL query to be sorted by the number of filled in columns. 我希望按填充列数对SQL查询的结果进行排序。 The rows with the least empty columns at the top, the ones with the most empty columns at the bottom. 空列最少的行在顶部,空列最多的行在底部。 Do any of you guys have an idea how to do this? 你们中有人有一个如何做的主意吗?

I thought about adding an extra column to the table which if updated every time the user edits their row, this number would indicate the number of empty columns and I could sort my list with that. 我考虑过要在表中添加一个额外的列,如果用户每次编辑其行时都进行了更新,则该数字将指示空列的数量,我可以以此对列表进行排序。 This however, sounds like unnecessary troubles, but maybe there is no other way? 但是,这听起来像是不必要的麻烦,但是也许没有其他方法了吗? I'm sure somebody on here will know! 我敢肯定这里的人会知道的!

Thanks, 谢谢,

Sander 桑德

You can do it in just about any database with a giant case statement: 您可以在带有巨大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

You could order by the amount of empty columns: 您可以按空列的数量进行排序:

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

(Note the + at the end of the lines: it's only one column with the integer count of empty fields, sorted in ascending order.) (请注意,在行的最后加上+ :这只是一列,其中空字段是整数,以升序排列。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM