我有以下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首先为空的情况,然后按字母顺序对列的其余部分进行排序。这样的事情是否可能?
答案 0 :(得分: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
答案 1 :(得分:2)
你可以试试这个:
ORDER BY
CASE WHEN e.entity_name IS NULL
THEN 0
ELSE w.financial_year END
,e.entity_name
答案 2 :(得分: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