有交易流水表bank_records表,包含两个字段:KH(银行卡号),JYSJ(交易时间) 1. 计算2023年每个月,每个银行卡号连续交易的最多天数 2. 计算2023年每个月,连续2天都有交易的银行卡号 3. 计算2023年每个月,连续5天都有交易的银行卡数量
时间: 2024-05-01 07:23:36 浏览: 68
1. 计算2023年每个月,每个银行卡号连续交易的最多天数
可以使用MySQL的日期函数和窗口函数来实现。首先,我们需要将JYSJ字段转换为日期类型,并按照KH和日期进行排序。然后,将KH和日期作为窗口分区,计算每个交易的日期与前一笔交易的日期之间的差值。如果差值为1,则表示两笔交易是连续的。接着,使用SUM函数将连续交易的天数累加起来,最后使用MAX函数找出每个银行卡号在每个月的最大连续交易天数。
示例SQL代码如下:
```
SELECT
KH,
DATE_FORMAT(JYSJ, '%Y-%m') AS Month,
MAX(ContinuityDays) AS MaxContinuityDays
FROM
(
SELECT
KH,
JYSJ,
DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY KH, DATE_FORMAT(JYSJ, '%Y-%m') ORDER BY JYSJ)) AS DiffDays,
CASE
WHEN DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY KH, DATE_FORMAT(JYSJ, '%Y-%m') ORDER BY JYSJ)) = 1 THEN 1
ELSE 0
END AS ContinuityDays
FROM
bank_records
WHERE
YEAR(JYSJ) = 2023
) AS t
GROUP BY
KH,
DATE_FORMAT(JYSJ, '%Y-%m')
```
2. 计算2023年每个月,连续2天都有交易的银行卡号
可以使用MySQL的日期函数和窗口函数来实现。首先,我们需要将JYSJ字段转换为日期类型,并按照日期和KH进行排序。然后,将KH和日期作为窗口分区,计算每个交易的日期与前一笔交易的日期之间的差值。如果差值为1,则表示两笔交易是连续的。接着,使用LAG函数和LEAD函数分别获取前一笔交易和后一笔交易的日期,判断当前交易是否与前后两笔交易都连续。最后,使用DISTINCT关键字去除重复的银行卡号。
示例SQL代码如下:
```
SELECT
DISTINCT KH,
DATE_FORMAT(JYSJ, '%Y-%m') AS Month
FROM
(
SELECT
KH,
JYSJ,
DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ)) AS DiffDays,
CASE
WHEN DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ)) = 1 AND DATEDIFF(LEAD(JYSJ) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ), JYSJ) = 1 THEN 1
ELSE 0
END AS ContinuityDays
FROM
bank_records
WHERE
YEAR(JYSJ) = 2023
) AS t
WHERE
ContinuityDays = 1
```
3. 计算2023年每个月,连续5天都有交易的银行卡数量
可以使用MySQL的日期函数和窗口函数来实现。首先,我们需要将JYSJ字段转换为日期类型,并按照日期和KH进行排序。然后,将KH和日期作为窗口分区,计算每个交易的日期与前一笔交易的日期之间的差值。如果差值为1,则表示两笔交易是连续的。接着,使用LAG函数和LEAD函数分别获取前一笔交易和后一笔交易的日期,判断当前交易是否与前后四笔交易都连续。最后,使用COUNT函数统计每个月连续5天都有交易的银行卡数量。
示例SQL代码如下:
```
SELECT
DATE_FORMAT(JYSJ, '%Y-%m') AS Month,
COUNT(DISTINCT KH) AS CountKH
FROM
(
SELECT
KH,
JYSJ,
DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ)) AS DiffDays,
CASE
WHEN DATEDIFF(JYSJ, LAG(JYSJ) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ)) = 1 AND DATEDIFF(LEAD(JYSJ, 1) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ), JYSJ) = 1 AND DATEDIFF(LEAD(JYSJ, 2) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ), JYSJ) = 2 AND DATEDIFF(LEAD(JYSJ, 3) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ), JYSJ) = 3 AND DATEDIFF(LEAD(JYSJ, 4) OVER (PARTITION BY DATE_FORMAT(JYSJ, '%Y-%m'), KH ORDER BY JYSJ), JYSJ) = 4 THEN 1
ELSE 0
END AS ContinuityDays
FROM
bank_records
WHERE
YEAR(JYSJ) = 2023
) AS t
WHERE
ContinuityDays = 1
GROUP BY
DATE_FORMAT(JYSJ, '%Y-%m')
```
阅读全文