我确定这是一个相当微不足道的问题,但我不确定谷歌要找到什么解决方案。
我有一个看起来像这样的表:
CREATE TABLE IF NOT EXISTS `transactions` (
`name` text collate utf8_swedish_ci NOT NULL,
`value` decimal(65,2) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=COMPACT;
我通过剪切和粘贴我的网上银行服务中的数据来填充这一点。 值可以是负值或正值,日期和名称包含的值应该相当明显;) 我构建了一个查询,让我看看每个月的底线:
SELECT sum(`value`) as 'change', DATE_FORMAT(`date`, '%M %Y') as 'month'
FROM `transactions`
WHERE 1
GROUP BY year(`date`), month(`date`)
现在,我想在月底将帐户中的累计总金额作为附加列添加。
SELECT sum(`value`) as 'change', DATE_FORMAT(`date`, '%M %Y') as 'month',
(SELECT sum(`value`) FROM `transactions` WHERE `date` <= 123) as 'accumulated'
FROM `transactions`
WHERE 1
GROUP BY year(`date`), month(`date`)
123并不是我想要的,但我不明白如何从该子查询中的DATE_FORMAT得到结果。
这是解决问题的正确方法吗?
这主要是个人练习(在非常小的数据集上运行)所以我不太关心性能,可读的SQL更为重要。
我在MySQL 5.0.45上运行InnoDB表
答案 0 :(得分:2)
SELECT change,
CONCAT(mymonth, ' ', myyear) AS 'month',
(
SELECT SUM(`value`)
FROM `transactions`
WHERE `date` < DATE_ADD(STR_TO_DATE(CONCAT('01.', mymonth, '.', myyear, '%D.%M.%Y'), INTERVAL 1 MONTH))
)
FROM (
SELECT sum(`value`) as 'change', YEAR(date) AS myyear, MONTH(date) AS mymonth
FROM `transactions`
WHERE 1
GROUP BY
YEAR(`date`), MONTH(`date`)
) q
你写道,你不是为了性能,但这种语法并不复杂,但效率更高(以防万一):
SELECT SUM(value) AS change,
CONCAT(MONTH(`date`), ' ', YEAR(`date`)) AS 'month',
@r : = @r + SUM(value) AS cumulative
FROM (
SELECT @r := 0
) AS vars,
transactions
WHERE 1
GROUP BY
YEAR(`date`), MONTH(`date`)
ORDER BY
YEAR(`date`), MONTH(`date`)
这个也将计算累计SUM
,但每个月只计算一次。