1

我有以下 SQL 查询:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name

通过我的排序,我想先显示 e.entity_name 为空的情况,然后按字母顺序对列的其余部分进行排序。这可能吗?

4

3 回答 3

3

当然,

  SELECT w.financial_year,
    ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + 
        ' is not available on the entity table. Please add.') ,
    COUNT(w.form_guid)
  FROM portal.workflow AS w
     LEFT JOIN property.entity AS e
         ON w.integer_1 = e.entity_id
  GROUP BY case When e.entity_name Is Null Then 0 Else 1 End,
        w.financial_year, w.integer_1, e.entity_name
  ORDER BY case When e.entity_name Is Null Then 0 Else 1 End, 
      w.financial_year, e.entity_name
于 2012-11-29T04:36:42.503 回答
2

你可以试试这个:

ORDER BY
        CASE WHEN e.entity_name IS NULL 
             THEN 0 
             ELSE w.financial_year END 
        ,e.entity_name

看到这个 SQLFiddle

于 2012-11-29T04:47:23.600 回答
0

在 ORDER BY 子句中使用 NULLS FIRST 或 NULLS LAST,如下所示:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name NULLS FIRST
于 2012-11-29T04:58:46.363 回答