SQL根据日期压缩行

时间:2015-08-13 19:18:01

标签: sql

我有一个数据表,如:

CategoryID    CustomerID    FromDate    ToDate
1             A             10/1/15     20/2/15
2             A             5/1/15      10/1/15
3             C             3/2/15      12/2/15
4             C             5/3/15      20/2/15
5             C             10/3/15     25/2/15

我需要按客户压缩/分组,采用最小的FromDate和最大ToDate以及最大的CategoryID。

CategoryID    CustomerID    FromDate    ToDate
2             A             5/1/15      20/2/15 
5             C             3/2/15      25/2/15

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这是一个非常简单的聚合,在您的CustomerId上进行分组。

Select  Max(CategoryId) As CategoryId, 
        CustomerId, 
        Min(FromDate)   As FromDate, 
        Max(ToDate)     As ToDate
From    Table
Group By CustomerId

答案 1 :(得分:1)

SELECT CategoryID, t.CustomerID, MIN(FromDate), MAX(ToDate)
FROM Table1 as t
INNER JOIN (SELECT CustmerID as CustomerId,MAX(CategoryID) as MaxCategoryID FROM Table1 GROUP BY CustomerID) as a 
ON t.CustomerID=a.CustomerID and CategoryId=a.MaxCategoryID
GROUP BY t.CustomerID, CategoryID