简体   繁体   English

用最小日期和最大日期合并记录

[英]Consolidate records with min date and max date

I have two rows of data in a SQL Server query and need to consolidate them into one column by criteria of min date for one column and max date for the second column.我在 SQL Server 查询中有两行数据,需要按照一列的最小日期和第二列的最大日期的条件将它们合并到一列中。

Example data:示例数据:

OrderID   PrevCFS   NewCFS   ChangeTime
---------------------------------------------------
   1        75         25    2018-10-31 08:00:00
   2        25          0    2018-10-31 09:00:00

I need them to be combined using the earliest date for PrevCFS and the latest date for NewCFS as there could be more than two records:我需要他们使用的最早日期组合PrevCFS和最新的日期NewCFS因为可能有两个以上的记录:

Results:结果:

PrevCFS   NewCFS   ChangeTime
---------------------------------------------------
  75        0      2018-10-31 09:00:00

The OrderID and Change time are not important in the results. OrderID和 Change time 在结果中并不重要。

You can try to use MAX and MIN aggregate function. 您可以尝试使用MAXMIN聚合函数。

SELECT MAX(PrevCFS) PrevCFS,
       MIN(NewCFS) NewCFS,
       MAX(ChangeTime) ChangeTime
FROM T
select
  (
    select top 1 PrevCFS
    from MyTable
    order by ChangeTime asc
  )
  ,
  (
    select top 1 NewCFS
    from MyTable
    order by ChangeTime desc
  )

You can get the most recent columns by ordering descending, and the older columns by ordering ascending. 您可以按降序排列获得最新的列,而按升序排列可以获取较旧的列。

Here is one way to combine them: 这是组合它们的一种方法:

select top (1) eprev.OldCFS, e.NewCFS, e.ChangeTime
from example e cross join
     (select top (1) e2.*
      from example e2
      order by e.ChangeTime asc
     ) eprev
order by e.ChangeTime desc

Is this helpful.? 这有帮助吗?

    Declare @T Table(OrderId int,PrevCFS int, NewCFS int,ChangeTime DATETIME)

    Insert into @T
    SELECT 1,75,25,'2018-10-31 08:00:0' Union All
    SELECT 2,25,0,'2018-10-31 09:00:00'

    Select t1.PrevCFS,t2.NewCFS,t2.ChangeTime from @T t1
    INNER JOIN @T t2 on t1.NewCFS=t2.PrevCFS

output: 输出:

    PrevCFS    NewCFS           ChangeTime
------------------------------------------------
      75         0       2018-10-31 09:00:00.000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM