【问题标题】:Order by Empty String Last on Concatenated Column按连接列上的最后一个空字符串排序
【发布时间】:2018-09-21 21:35:51
【问题描述】:

我正在尝试按字母顺序对表格进行排序,升序,最后使用空值,但遇到了问题。

下面的代码产生以下错误:

如果指定了 SELECT DISTINCT,则 ORDER BY 项目必须出现在选择列表中。

select distinct 
'item' = othertab..item,
'stockedFor' = tab..stocked_for
          + ', ' + tab..stockedFor2
          + ', '+ tab..stockedFor3

from tab

order by case when stockedFor is null then 1 else 0 end, stockedFor

如何按字母顺序返回stockedFor,最后返回空值?

【问题讨论】:

    标签: sql-server sql-order-by


    【解决方案1】:

    只需将其包装在另一个 select 语句中:

    select stockedFor
    from (
           select distinct 
           'stockedFor' = tab..stocked_for
                     + ', ' + tab..stockedFor2
                     + ', '+ tab..stockedFor3
           from tab
         ) x
    order by case when stockedFor is null then 1 else 0 end, stockedFor
    

    【讨论】:

      【解决方案2】:

      由于您要删除重复项,因此解决方法是使用GROUP BY 而不是DISTINCT 来删除重复项。问题已经改变,但如果将所有列放在SELECT 中的GROUP BY 中,该方法仍然适用。

      例如:

      select 
      'item' = othertab..item,
      'stockedFor' = tab..stocked_for
                + ', ' + tab..stockedFor2
                + ', '+ tab..stockedFor3
      
      from tab
      GROUP BY othertab..item,
               tab..stocked_for
                + ', ' + tab..stockedFor2
                + ', '+ tab..stockedFor3
      
      order by case when stockedFor is null then 1 else 0 end, stockedFor
      

      【讨论】:

      • 不确定当您将另一个变量添加到 select 语句时此方法是否仍然有效。我在这个问题的第一个版本中省略了它。我使用这种方法得到以下错误,Column 'othertab..item' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
      • 如果SELECT 中的每一列 都包含在GROUP BY 中,则使用GROUP BY 获取不同的值将起作用。在提到的这个错误中,othertab...item 列未包含在GROUP BY 中。错误提示问题:'othertab..item 在选择列表中无效,因为......它不包含在...... GROUP BY 子句中。”
      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2016-10-07
      • 2015-09-27
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多