【问题标题】:SQL: How can I select the first and last date for each customer?SQL:如何为每个客户选择第一个和最后一个日期?
【发布时间】:2014-04-22 22:28:52
【问题描述】:

我似乎无法弄清楚这一点。我有一张交易表(很多),包括日期、客户 ID 等。

我想为特定日期选择当天每个客户的第一笔和最后一笔交易的日期时间,如下所示:

custID FirstT  LastT
318    08:05   18:35
968    03:21   13:54
488    12:34   14:28

SQL Server 2008。听起来很简单,但我已经准备好认输了……不胜感激……

【问题讨论】:

    标签: sql tsql


    【解决方案1】:
    SELECT
      custID,
      MIN(transaction_date)  AS FirstT,
      MAX(transaction_date)  AS LastT
    FROM
      yourTable
    WHERE
          transaction_date >= '2014-04-01'
      AND transaction_date <  '2014-04-02'
    GROUP BY
      custID
    

    【讨论】:

    • 那……太简单了,我现在觉得很蠢…… :) 谢谢!!而且我想我终于明白了 group by 子句...
    【解决方案2】:

    试试这个:

    SELECT custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date)) Date, MIN(date) FirstT, MAX(date) LastT
    FROM transactions
    GROUP BY custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date))
    

    【讨论】:

      【解决方案3】:

      不知道你的架构,但你应该这样做:

          select custID, max(transactionDate), min(transactionDate)
      where cast(transactionDate as date) = '20140101'
          group by custID
      

      【讨论】:

      • 据我所知; where cast(transactionDate as date) = '20140101' 将阻止在 transactionDate 上使用任何索引。
      • cast(transactionDate as date) 不等于'20140101'`
      • @MatBailie - 我之前已经被一些专家提出来了。事实上,迄今为止的转换不会阻止索引的使用。有逻辑可以识别这种情况。见What is the most efficient way to trim time from datetime
      • @Damien_The_Unbeliever - 谢谢你,知道有用。我心中已经有了足够多的疑问,我可以在它前面加上As far as I am aware; :) 我想我会坚持使用&gt;= AND &lt;,现在我只需要怀疑我这样做是否合理。
      • @MatBailie - 只是在编辑我之前的评论以包含指向 Aaron Bertrand 文章的链接
      【解决方案4】:
      SELECT * FROM 
        (SELECT custID, transaction_date FROM transactions ORDER BY transaction_date LIMIT 1) t
      UNION
      SELECT * FROM 
        (SELECT custID, transaction_date FROM transactions ORDER BY transaction_date DESC LIMIT 1) t1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-08
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-18
        相关资源
        最近更新 更多