需要以下格式的SQL结果集

时间:2019-05-23 07:16:46

标签: sql

我的表格格式如下

ID  TotalAmount AdjStatus
--------------------------
1   0           Approved
2   0           Closed
3   0           Disputed

我需要基于列值AdjStatus的多行结果集,如下所示。

ID  TotalAmount AdjStatus
---------------------------------
1   0           Approved
1   null        Closed
1   null        Disputed
2   0           Closed
2   null        Approved
2   null        Disputed
3   0           Disputed
3   null        Approved
3   null        Closed

1 个答案:

答案 0 :(得分:3)

尝试在以下情况下使用CROSS JOIN

select 
    t.Id, 
    case when t.AdjStatus <> t2.AdjStatus then null else t.TotalAmount end as TotalAmount,
    t2.AdjStatus
from #test as t
cross join #test t2
order by t.Id, case when t.AdjStatus <> t2.AdjStatus then null else t.TotalAmount end desc

您可以在SQL Fiddle

进行测试