在SQL Server中选择第一个和最后一个日期的值

时间:2015-09-01 09:06:49

标签: sql sql-server

今天我遇到了我需要为实体选择初始值(使用最早的日期)和最终值(带有最后日期)值的任务。我已设法通过多个OVER进行此操作,但看起来这将是prod数据的性能问题。

有没有办法优化我的解决方案?

SELECT DISTINCT 
    InvoiceID, 
    FIRST_VALUE(ih.ApprovedTotal) OVER (PARTITION BY InvoiceID ORDER BY ih.DateReviewed ASC) AS InitialTotal, 
    FIRST_VALUE(ih.DateReviewed) OVER (PARTITION BY InvoiceID ORDER BY ih.DateReviewed ASC) AS Initialdate, 
    LAST_VALUE(ih.ApprovedTotal) OVER (PARTITION BY InvoiceID ORDER BY ih.DateReviewed ASC) AS FinalTotal,
    LAST_VALUE(ih.DateReviewed) OVER (PARTITION BY InvoiceID ORDER BY ih.DateReviewed ASC) AS FinalDate
FROM  
    tblInvoiceHistory ih

编辑:如果我们有这些数据:

    InvoiceId  |  DateReviewed  |  ApprovedTotal
    --------------------------------------------
1   1          |  2015-1-1      |  10
2   1          |  2015-2-1      |  20
3   1          |  2015-3-1      |  30
4   2          |  2015-1-1      |  110
5   2          |  2015-2-1      |  120
6   2          |  2015-3-1      |  130

所需的输出将是这样的

    InvoiceId  |  InitialDate  |  InitialTotal  |  FinalDate  |  FinalTotal
    -----------------------------------------------------------------------
1   1          |  2015-1-1     |  10            |  2015-3-1   |  30
2   2          |  2015-1-1     |  110           |  2015-3-1   |  130

1 个答案:

答案 0 :(得分:3)

SELECT 
     InvoiceID
    ,[Initialdate] = MIN(ih.DateReviewed)
    ,[Finaldate]   = MAX(ih.DateReviewed)
FROM tblInvoiceHistory ih
GROUP BY InvoiceID

编辑:

WITH cte AS(
  SELECT 
     [InvoiceId]   = InvoiceID
    ,[MinDate]     = MIN(ih.DateReviewed)  
    ,[MaxDate]     = MAX(ih.DateReviewed)  
  FROM tblInvoiceHistory ih
  GROUP BY InvoiceID
  )
  SELECT  
    c.InvoiceId
   ,[InitialDate]  = c.[MinDate]
   ,[FinalDate]    = c.[MaxDate]
   ,[InitialTotal] = (SELECT ApprovedTotal FROM tblInvoiceHistory ih WHERE ih.InvoiceId = c.InvoiceId AND ih.DateReviewed = c.[MinDate])
   ,[FinalTotal]   = (SELECT ApprovedTotal FROM tblInvoiceHistory ih WHERE ih.InvoiceId = c.InvoiceId AND ih.DateReviewed = c.[MaxDate])
  FROM cte c