按时间顺序排列

时间:2016-05-02 15:02:23

标签: sql sql-server sql-server-2008 tsql

我试图从按客户ID和状态分组的表格中获取每个状态的最高结果,按时间排序。

给出的数据:

CustNo Date       Status
 1      2016-03-24 C
 1      2016-02-08 C
 1      2016-01-17 A
 1      2015-12-04 C
 2      2016-04-28 B
 2      2016-03-25 C
 2      2016-02-13 C
 2      2016-01-04 C
 3      2016-02-02 A
 3      2016-01-09 A
 3      2015-12-12 A
 3      2015-11-30 A

我希望输出看起来像这样:

CustNo Date       Status
1      2016-03-24 C
1      2016-01-17 A
1      2015-12-04 C
2      2016-04-28 B
2      2016-03-25 C
3      2016-02-02 A

如您所见,我希望每个客户的每个状态更改(如果有)的最新日期。我为客户2和3解决了这个问题,其中状态没有变化或状态永远不会改变,但对于客户1,状态已从C更改为A并返回到C,这是一个棘手的部分(至少对我来说) )。我似乎总是将C状态组合在一起。

2 个答案:

答案 0 :(得分:0)

你可以试试这个。

With CTE as 
{
    select CustNo,
            DATE,
            Status,
            ROW_NUMBER () over (partition by CustNo order by date) as ord
    from tab
)

SELECT  CustNo,
        DATE,
        Status
FROM CTE
EXCEPT
SELECT  C1.CustNo,
        C1.DATE,
        C1.Status
FROM CTE C1
    INNER JOIN CTE C2 ON C1.CustNo = C2.CustNo 
                        AND C1.Status = C2.Status
                        AND C1.ord + 1 = C2.ord

答案 1 :(得分:0)

您可以使用窗口函数ROW_NUMBER来计算组:

WITH cte AS (
  SELECT *,
     ROW_NUMBER() OVER(PARTITION BY CustNo ORDER BY Date) -
     ROW_NUMBER() OVER(PARTITION BY CustNo, Status ORDER BY Date) AS grp
  FROM mytable
)
SELECT CustNo, Status, MAX(Date) AS Date
FROM cte
GROUP BY CustNo, Status, grp
ORDER BY CustNo, Date DESC;

LiveDemo

输出:

╔════════╦════════╦═════════════════════╗
║ CustNo ║ Status ║        Date         ║
╠════════╬════════╬═════════════════════╣
║      1 ║ C      ║ 24.03.2016 00:00:00 ║
║      1 ║ A      ║ 17.01.2016 00:00:00 ║
║      1 ║ C      ║ 04.12.2015 00:00:00 ║
║      2 ║ B      ║ 28.04.2016 00:00:00 ║
║      2 ║ C      ║ 25.03.2016 00:00:00 ║
║      3 ║ A      ║ 02.02.2016 00:00:00 ║
╚════════╩════════╩═════════════════════╝