SQL聚合记录的运行计数

时间:2014-01-07 13:35:27

标签: mysql sql

我对SQL比较陌生,所以对任何愚蠢的问题表示道歉,但我甚至无法接近这一点。

我有一个客户订单数据集,其中包含 Cust_ID 日期。我想返回一个查询,其中包含所有客户订单,添加两个字段,“首次订购日期”和“订单计数”

Cust_ID    Date        FirstOrder     orderCount
5001       04/10/13    04/10/13       1
5001       11/10/13    04/10/13       2
5002       11/10/13    11/10/13       1
5001       17/10/13    04/10/13       3
5001       24/10/13    04/10/13       4
5002       24/10/13    11/10/13       2

任何指针都会非常感激。

由于

3 个答案:

答案 0 :(得分:1)

SELECT foo.Cust_ID
     , foo.`Date`
     , MIN(p.`Date`) AS FirstOrder
     , COUNT(*) AS orderCount
FROM foo
JOIN foo AS p
  ON p.Cust_id = foo.Cust_id
    AND p.`Date` <= foo.`Date`
GROUP BY foo.Cust_ID, foo.`Date`
ORDER BY foo.`Date`;

答案 1 :(得分:0)

如果我理解正确的话:

您拥有的源数据:

Cust_ID    Date
5001       04/10/13   
5001       11/10/13   
5002       11/10/13   
5001       17/10/13  
5001       24/10/13    
5002       24/10/13    

您期望的结果数据集:

Cust_ID    Date        FirstOrder     OrderNumber
5001       04/10/13    04/10/13       1
5001       11/10/13    04/10/13       2
5002       11/10/13    11/10/13       1
5001       17/10/13    04/10/13       3
5001       24/10/13    04/10/13       4
5002       24/10/13    11/10/13       2

然后查询应该是(如果使用AF):

SELECT Cust_ID, Date,
       MIN(Date) over ( partition by Cust_ID ) as FirstOrder,
       RowNumber() over ( partition by Cust_ID order by Date asc ) as OrderNumber
FROM   Orders

仅使用标准SQL排除AF:

SELECT S.Cust_ID, S.Date, MIN(J.Date) as FirstDate, Count(S.Cust_id)
FROM Orders S
INNER JOIN Orders J
ON S.Cust_ID = J.Cust_ID and S.Date >= J.Date
GROUP BY S.Cust_id, S.Date

答案 2 :(得分:0)

你可以尝试一下吗?

SELECT tab.Cust_ID, tab.Date, x.FirstOrder, x.orderCount
FROM tab INNER JOIN (
    SELECT Cust_ID, MIN(Date) AS FirstOrder,
        COUNT(*) AS orderCount
    FROM tab
    GROUP BY CustID
) x ON tab.Cust_ID = x.Cust_ID

内部查询为每位客户选择FirstOrderorderCount,最后为每个订单加入。

更新

使用user variables,您可以跟踪Cust_ID

的订单计数顺序
SELECT *
FROM (
    SELECT tab.Cust_ID, tab.Date AS Date, x.FirstOrder, x.orderCount,
        IF(@prev_cust_id = tab.Cust_ID, @cnt := @cnt + 1, @cnt := 1)
    FROM tab INNER JOIN (
        SELECT Cust_ID, MIN(Date) AS FirstOrder,
            COUNT(*) AS orderCount
        FROM tab
        GROUP BY CustID
    ) x ON tab.Cust_ID = x.Cust_ID,
    (SELECT @prev_cust_id := 0, @cnt := 1) y
    ORDER BY tab.Cust_ID
) x
ORDER BY Date;