CREATE TABLE IF NOT EXISTS `记账` (
`id` int NOT NULL AUTO_INCREMENT,
`日期` timestamp NULL DEFAULT NULL,
`余额` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `记账` (`id`, `日期`, `余额`) VALUES
(1, '2020-03-10 11:16:04', 150),
(2, '2020-03-09 11:16:11', 120),
(3, '2020-03-08 11:16:24', 130),
(4, '2020-03-07 11:16:34', 120);
SQL语句:
SELECT *,今日-昨日 AS 差额 FROM
(
SELECT
MAX(case when DATEDIFF(日期,NOW())=0 then 余额 ELSE 0 END) AS 今日,
MAX(case when DATEDIFF(日期,NOW())=-1 then 余额 ELSE 0 END) AS 昨日
FROM 记账
WHERE DATEDIFF(日期,NOW()) BETWEEN -1 and 0
)AS t
为了方便理解,直接上中文表名和列名了。
SQL语句:
查询结果:
今日 昨日 差额
150 120 30