【发布时间】: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。听起来很简单,但我已经准备好认输了……不胜感激……
【问题讨论】:
我似乎无法弄清楚这一点。我有一张交易表(很多),包括日期、客户 ID 等。
我想为特定日期选择当天每个客户的第一笔和最后一笔交易的日期时间,如下所示:
custID FirstT LastT
318 08:05 18:35
968 03:21 13:54
488 12:34 14:28
SQL Server 2008。听起来很简单,但我已经准备好认输了……不胜感激……
【问题讨论】:
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
【讨论】:
试试这个:
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))
【讨论】:
不知道你的架构,但你应该这样做:
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'`
As far as I am aware; :) 我想我会坚持使用>= AND <,现在我只需要怀疑我这样做是否合理。
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
【讨论】: