使用 Union 和 null 值进行排序 SQL Server
我不知道如何对以下联合查询的第二个选择语句中的数据进行排序。
期望的结果是:
C null null null null null
I xxxx xxxx xxxx 1 xxxx
I xxxx xxxx xxxx 1 xxxx
I xxxx xxxx xxxx null xxxx
I xxxx xxxx xxxx null xxxx
这是代码:
select 'C' [Identifier]
,null [Acct/Invoice #]
,null [Check #/Pay Amount]
,null [Check Amount/Error Code]
,null [Error Flag]
,null [Trx Account #]
union all
select 'I' [Indentifer]
,final_inv_number [Invoice #]
,final_final_pay_amount [Pay Amount]
,final_trans_code [Error Code]
,case when final_is_reconciled = 1 then 1 end [Error Flag]
,case when final_parse_type = 'ERROR CREATED' or final_parse_type = 'PREV PD'
then final_account_number else null end [Trx Account #]
from #final
where final_net_pay_amount <> 0
--order by [Error Flag] ?
I am at a loss of how to sort the data in the second select statement of the following union query.
The desired results would be:
C null null null null null
I xxxx xxxx xxxx 1 xxxx
I xxxx xxxx xxxx 1 xxxx
I xxxx xxxx xxxx null xxxx
I xxxx xxxx xxxx null xxxx
Here is the code:
select 'C' [Identifier]
,null [Acct/Invoice #]
,null [Check #/Pay Amount]
,null [Check Amount/Error Code]
,null [Error Flag]
,null [Trx Account #]
union all
select 'I' [Indentifer]
,final_inv_number [Invoice #]
,final_final_pay_amount [Pay Amount]
,final_trans_code [Error Code]
,case when final_is_reconciled = 1 then 1 end [Error Flag]
,case when final_parse_type = 'ERROR CREATED' or final_parse_type = 'PREV PD'
then final_account_number else null end [Trx Account #]
from #final
where final_net_pay_amount <> 0
--order by [Error Flag] ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在对整个结果进行排序,而不仅仅是第二个选择中的记录。
您可以使用 [Identifier] 字段来保留第一个选择的记录:
You are sorting the entire result, not just the records from the second select.
You can use the [Identifier] field to keep the records from the first select first:
ORDER BY
在UNION ALL
或其他集合运算符之后计算。因此,您应该使用子选择,在这些子选择语句上运行ORDER BY
,计算分配递增行号的伪列,然后按外部语句中的伪列的值进行排序。ORDER BY
is computed afterUNION ALL
or other set operators. Therefore you should use subselects runORDER BY
on those subselect statements, compute a pseudocolumn that assigns an increasing row number, and then order by the value of the pseudocolumn in the outer statement.