mysql - 自上次购买以来的时间

标签 mysql sql optimization

所以我在数据库中有一个包含以下字段的表:

  • 交易 ID
  • 客户 ID
  • 交易日期

我想向名为的表添加一个附加字段

  • 每位客户自上次交易以来的时间

这应该只是(交易日期 A - 交易日期 B),前提是客户相同并且表格按日期排序。

我正在使用 mySQL(因此没有 Oracle Advances PL/SQL)。我的表有很多行。

从 txns 中选择 txn_id、cust_id、txn_date;

我该怎么做?

最佳答案

我认为使用相关子查询最容易做到这一点:

select t.*,
       datediff((select t2.TransactionDate
                 from t t2
                 where t2.CustomerId = t.CustomerId and
                       t2.TransactionDate < t.TransactionDate
                 order by t2.TransactionDate desc
                 limit 1
                ), t.TransactionDate) as daysSinceLastPurchase
from t;

这假设交易发生在不同的日子。

如果这个假设不成立并且事务 ID 按升序排列,您可以使用:

select t.*,
       datediff((select t2.TransactionDate
                 from t t2
                 where t2.CustomerId = t.CustomerId and
                       t2.TransactionId < t.TransactionId
                 order by t2.TransactionId desc
                 limit 1
                ), t.TransactionDate) as daysSinceLastPurchase
from t;

关于mysql - 自上次购买以来的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277282/

相关文章:

c++ - 将 void 函数作为参数传递给 c++ 中的 double 函数

php - 使用内部联接选择 COUNT

mysql - 由于 secure_file_priv 原因,无法在 MySQL Server 8.0 上导入 txt 文件

mysql - 意外行为 : Subtraction between null values results in '0'

sql - Access SQL - ALTER COLUMN 到自动编号?

linux - 来自 gcc 的 pgo 的优化报告

MYSQL双条件计数

mysql - 无法在同一个查询中运行 Insert 和 Select LAST_INSERT_ID()?

SQL 存储过程 if 语句带位

Java 最佳实践静态最终映射值