我在MySQL中有一个表,其中包含一个date
,type
,一个site_id
和一个value
我想获得当年和去年的值的增/减,但我似乎无法做到这一点,
首先-如果不包含行lossOrGain (previousFill - currentFill) AS 'Increase/Decrease'
,我如何实际减去这些值,我得到了我需要的值,但我无法如行中所示相互减去代码。
第二步-当我删除lossOrGain (previousFill - currentFill) AS 'Increase/Decrease'
时,每个站点的值都相同,它仅采用第一个站点的值并将其应用于所有其他站点,
网站|先前值|当前值
A | 1 | 2
B | 1 | 2
C | 1 | 2
我该如何解决?
这是我第一次在MySQL中执行此操作,但我尝试执行类似操作但失败了
SELECT s.name AS SiteName,
(SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date
BETWEEN DATE_SUB(:fromDate, INTERVAL 1 YEAR) AND DATE_SUB(:toDate, INTERVAL 1 YEAR)
-
SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate)
AS 'Increase/Decrease'
FROM management_information mi
LEFT JOIN site s
ON mi.site_id = s.id
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate;
最后显示以下代码
(SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN DATE_SUB(:fromDate, INTERVAL 1 YEAR) AND DATE_SUB(:toDate, INTERVAL 1 YEAR)) previousFill,
(SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate) currentFill,
lossOrGain (previousFill - currentFill) AS 'Increase/Decrease'
FROM management_information mi
LEFT JOIN site s
ON mi.site_id = s.id
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate;
我希望与去年相比,特定月份的所有网站的价值都有增减
网站:A
增/减:(去年的值-今年的值)
所以我需要帮助
因为我很困惑,我该怎么办?
编辑:
我设法正确计算数学并获得了Increase/Decrease
值,现在我需要为相关站点获取适当的值,这就是我所做的
SELECT s.name AS SiteName,
((SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date
BETWEEN DATE_SUB(:fromDate, INTERVAL 1 YEAR) AND DATE_SUB(:toDate, INTERVAL 1 YEAR)) -
(SELECT AVG(mi.value)
FROM management_information mi
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate)) AS 'Increase/Decrease'
FROM management_information mi
LEFT JOIN site s
ON mi.site_id = s.id
WHERE mi.type = 'AVERAGE_FILL'
AND mi.date BETWEEN :fromDate AND :toDate;