1

我是 TSQL 的初学者,并希望获得有关 TSQL 条件的一些指导

有没有办法让同一个 SQL 字段作为不同的列进行查询?当文件从我们定义的不同状态移动时,我的字段名称会发生​​变化,我正在尝试使用状态变化中的相关时间戳来分析一些趋势。例如,文件的关联数据如下所示:

<File_History
Loanstatusdescriptor= “Underwrite Assigned” Status.EventTime= “4/1/2017 12:05”&gt;

<File_History
        Loanstatusdescriptor= “Closing Request Received” Status.EventTime= “4/3/2017 17:15”&gt;

我正在创建一份报告,该报告基于某些文件在工作流程中移动时的状态。查询是否类似于:

SELECT

LoanInfo.UnderwriterName

,File_History.Status.EventTime (IF loanstatusdescriptor= “Underwrite Assigned”) AS ‘Underwriter Assigned Date’

,File_History.Status.EventTime ( IF loanstatusdescriptor= “Closing Request Received”) AS ‘Closing Request Receieved Date’

……

最终产品看起来像

    Underwriter|Underwriter Assigned Date |Closing Request Received Date  
    Bobby Brown    4/1/2017                 4/3/2017
    Sally Jones    4/7/2017                 4/9/2017
    Chris Graff    4/6/2017                 4/17/2017

我将如何写出允许根据贷款状态创建列的 T-SQL 语句?

4

1 回答 1

1

假设File_History_Status是一个可以连接到的表LoanInfo

使用具有已知列数的条件聚合:

select 
    li.UnderwriterName
  , [Underwriter_Assigned_Date] = max(case 
      when fhs.LoanStatusDescriptor = 'Underwriter Assigned' 
        then fhs.EventTime 
      end)
  , [Closing_Request_Received_Date] = max(case 
      when fhs.LoanStatusDescriptor = 'Closing Request Received' 
        then fhs.EventTime 
      end)
from LoanInfo li
  inner join File_History_Status fhs
    on li.LoanId = fhs.LoanId
group by li.UnderwriterName
于 2017-04-05T17:03:55.747 回答