gpt4 book ai didi

mysql - 计算两个日期之间的差异

转载 作者:行者123 更新时间:2023-11-29 09:50:08 26 4
gpt4 key购买 nike

我有一个如下所示的表格。

CREATE TABLE `table_growth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` datetime DEFAULT CURRENT_TIMESTAMP,
`table_name` varchar(50) DEFAULT NULL,
`rows` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=184 DEFAULT CHARSET=utf8

表格中的行示例:

+-----+---------------------+--------------------------+-------+
| id | timestamp | table_name | rows |
+-----+---------------------+--------------------------+-------+
| 110 | 2019-03-01 06:00:00 | attachments | 640 |
| 111 | 2019-03-01 06:00:00 | contacts | 0 |
| 112 | 2019-03-01 06:00:00 | copy_menuitem_options | 3038 |
| 113 | 2019-03-01 06:00:00 | copy_menuitem_suboptions | 9779 |
| 114 | 2019-03-01 06:00:00 | copy_menuitems | 12118 |
| 115 | 2019-03-02 06:00:00 | attachments | 638 |
| 116 | 2019-03-02 06:00:00 | contacts | 0 |
| 117 | 2019-03-02 06:00:00 | copy_menuitem_options | 3039 |
| 118 | 2019-03-02 06:00:00 | copy_menuitem_suboptions | 9789 |
| 119 | 2019-03-02 06:00:00 | copy_menuitems | 12128 |
+-----+---------------------+--------------------------+-------+

我想计算 2 天之间的diff(rows)。就像date(timestamp)='2019-03-02' - date(timestamp)='2019-03-01'

预期结果

table_name              | Rows Diff
------------------------------
attachments | 2
contacts | 0
copy_menuitem_options | 1
copy_menuitem_suboptions| 10
copy_menuitems | 10

我尝试了这些查询,但在某个地方失败了。

 SELECT x.table_name
, (y.rows-x.rows)as diff
FROM dbadmin.table_growth x
JOIN dbadmin.table_growth y
ON y.id = x.id
AND DATE(y.timestamp) = '2019-03-02'
WHERE DATE(x.timestamp) = '2019-03-01';

select x.table_name, (y.rows - x.rows) as doff
from table_growth x join
table_growth y on y.id=x.id and DATE(y.timestamp) = '2019-03-02'
WHERE DATE(x.timestamp) = '2019-03-01';

最佳答案

您的第二个查询是在正确的轨道上,但连接条件部分关闭。您应该断言表名(而不是 ID)匹配:

SELECT
x.table_name,
(x.rows - y.rows) AS diff
FROM table_growth x
INNER JOIN table_growth y
ON x.table_name = y.table_name and
DATE(y.timestamp) = '2019-03-02'
WHERE
DATE(x.timestamp) = '2019-03-01';

注意:您当前的输出有点不明确,因为不清楚哪个 rows 值在差异中排在第一位,或者您是否想报告绝对值。

关于mysql - 计算两个日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com