如何根据另一列的条件两次查询同一列?

时间:2017-04-05 16:49:55

标签: sql sql-server-2008 tsql report-builder2.0

我是TSQL的初学者,希望能够获得有关TSQL条件的指导

是否有一种方法可以将相同的SQL字段作为不同的列进行查询?当文件从我们定义的不同状态移动时,我的字段名称会发生​​变化,并且我尝试使用状态更改中的关联时间戳来分析某些趋势。例如,文件的关联数据如下所示:

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

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

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

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语句?

1 个答案:

答案 0 :(得分: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