我需要一个关于MySQL的最后两个条目之间的区别的解决方案
SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date,
SUM(order_total_after_tax) as number
FROM tbl_order
WHERE status = 'Confirmed'
GROUP BY DATE_FORMAT(order_datetime,'%Y/%m')
Limit 2
输出:
date number
02/2019 2345.01
03/2019 103751.05
但是我需要一个精确的解决方案,就是我需要找到最后2个结果之间的差异
2345.01 -103751.05
结果:-101406.04
在MySQL中怎么做?查询是什么?
答案 0 :(得分:0)
您可以尝试交叉加入
select a.date, a.number, b.number, a.number - b.number my_diff
from (
SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date
, SUM(order_total_after_tax) as number
FROM tbl_order
where status='Confirmed'
GROUP BY DATE_FORMAT(order_datetime,'%Y/%m')
Limit 2
) a
CROSS JOIN (
SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date
, SUM(order_total_after_tax) as number
FROM tbl_order
where status='Confirmed'
GROUP BY DATE_FORMAT(order_datetime,'%Y/%m')
) b ON a.date = b.date and a.number <> b.number
答案 1 :(得分:0)
一种方法是cross join
,但它看起来像这样:
SELECT last.number - last_1.number
FROM (SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date,
SUM(order_total_after_tax) as number
FROM tbl_order
WHERE status = 'Confirmed'
GROUP BY DATE_FORMAT(order_datetime,'%Y/%m')
ORDER BY date
LIMIT 1
) as last CROSS JOIN
(SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date,
SUM(order_total_after_tax) as number
FROM tbl_order
WHERE status = 'Confirmed'
GROUP BY DATE_FORMAT(order_datetime,'%Y/%m')
ORDER BY date
LIMIT 1 OFFSET 1
) last_1
答案 2 :(得分:0)
SELECT last.number - last_1.number FROM (SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date, SUM(order_total_after_tax) as number FROM tbl_order WHERE status = 'Confirmed' GROUP BY DATE_FORMAT(order_datetime,'%Y/%m') ORDER BY date DESC LIMIT 1 ) as last CROSS JOIN (SELECT DATE_FORMAT(order_datetime,'%m/%Y') as date, SUM(order_total_after_tax) as number FROM tbl_order WHERE status = 'Confirmed' GROUP BY DATE_FORMAT(order_datetime,'%Y/%m') ORDER BY date DESC LIMIT 1 OFFSET 1 ) last_1