枢轴产生类似矩阵的输出而没有聚合函数

时间:2019-05-23 07:01:20

标签: sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我有三个桌子。

PeriodTable(始终持续4年)

**ID   Year**  
1     2016      
2     2017  
3     2018  
4     2019

StatusTable(始终为四个状态)

**ID   Status**  
1     Completed      
2     Open  
3     New  
4     Declained

TransactionTable

**Year  AccountName  TotalAmount    Status**    
2019    King         1000000.00     Declained   
2019    BlueBird     3800000.00     Completed      
2018    Heartly Inc  250000.00      Open        
2016    ABB Data     1500000.00     Completed       
2016    Delta        500000.00      Declained

预期输出: 总数状态来自TransactionTable * 4年。在这种情况下为20行。

**Year  AccountName  TotalAmount    Status**    
2019    King         1000000.00     Declained   
2019    BlueBird     3800000.00     Completed
2019    NULL            NULL        Open        
2019    NULL            NULL        Completed       
2019    NULL            NULL        Declained      
2018    NULL            NULL        Declained   
2018    NULL            NULL        Completed      
2018    Heartly Inc  250000.00      Open        
2018    NULL            NULL        Completed       
2018    NULL            NULL        Declained
2017    NULL            NULL        Declained   
2017    NULL            NULL        Completed      
2017    NULL            NULL        Open        
2017    NULL            NULL        Completed       
2017    NULL            NULL        Declained
2016    NULL            NULL        Declained   
2016    NULL            NULL        Completed      
2016    NULL            NULL        Open        
2016    ABB Data     1500000.00     Completed       
2016    Delta        500000.00      Declained

我尝试了Google提供的许多解决方案,但没有任何解决方案。 通过枢轴功能可以实现,因为我在这里不需要聚合选项。

1 个答案:

答案 0 :(得分:2)

尝试类似的方法:

select 
    p.Year, 
    case when p.Year <> t.Year then null else t.AccountName end as AccountName, 
    case when p.Year <> t.Year then null else t.TotalAmount end as TotalAmount, 
    t.Status
from #period as p
cross join #trans as t
order by p.Year desc

您可以在SQL Fiddle

进行测试