如何更新交易数据,包括第一个交易日期的日期和最新交易日期的地址?

时间:2017-09-11 10:15:18

标签: sql-server

我正在尝试使用日期作为第一个交易/购物日期和最新交易的地址来重新排列数据。数据包括不同日期的单个客户的交易。请帮忙。

enter image description here

Desired Out应该像:

enter image description here

1 个答案:

答案 0 :(得分:0)

由于缺少表格结构等,这里有一些“虚拟”代码。我们的想法是首先评估每个客户的最小和最大日期,然后在相应的记录之间进行连接:

WITH cte AS(
  SELECT [Customer Code_Transaction]) AS CustomerCode
        ,min([Invoice Date_Transaction]) AS MinDate
        ,max([Invoice Date_Transaction]) AS MaxDate
    FROM [yourtable...]
    GROUP BY [Customer Code_Transaction]
)
SELECT t1.[Invoice Date_Transaction]
      ,t1.[Customer Code_Transaction]
      ,t1.[Customer Name_Transaction]
      ,t2.[Address_CustReport]
   FROM [yourtable...] AS t1
   JOIN cte AS c ON c.MinDate = t1.[Invoice Date_Transaction] AND c.CustomerCode = t1.[Customer Code_Transaction]
   JOIN [yourtable...] AS t2 ON t2.[Customer Code_Transaction] = c.[Customer Code_Transaction] AND t2.[Invoice Date_Transaction] = c.MaxDate