正如您所看到的,今年和去年的结果是相同的,这就是问题所在。我想用得像。我想用一个当前年份和一个去年一个查询。
我可以在去年使用此YEAR(o.date_add) = YEAR(NOW() - INTERVAL 1 YEAR)
从今年起,我可以使用它,例如:YEAR(o.date_add) = YEAR(CURRENT_DATE())
我的查询:
SELECT
IFNULL(SUM(DISTINCT o.total_paid_tax_excl), 0) AS CurrentYEAR,
IFNULL(SUM(DISTINCT o.total_paid_tax_excl), 0) AS LastYEAR,
IFNULL(CONCAT(l.name), 0) AS name
FROM
expoled.ps_orders o
LEFT JOIN
expoled.ps_address a ON o.id_address_delivery = a.id_address
INNER JOIN
expoled.ps_country c ON a.id_country = c.id_country
INNER JOIN
expoled.ps_country_lang l ON c.id_country = l.id_country
WHERE
l.id_lang = 7
AND o.current_state IN (3 , 4, 5, 9, 13, 15, 20, 22, 23, 24, 25, 121)
AND l.name NOT IN ('Netherlands')
GROUP BY (l.name)
我可以进行单独查询,但我想在1个查询中如何实现这一点? 我确实尝试了Union,但结果保持不变。
我想要这样(这个不起作用!!仅举例如[photoshop]
我想我需要更改查询的这一部分
SELECT
IFNULL(SUM(o.total_paid_tax_excl), 0) AS CurrentYEAR,
IFNULL(SUM(o.total_paid_tax_excl), 0) AS LastYEAR,
IFNULL(CONCAT(l.name), 0) AS name
FROM
并将其添加到我的查询
对于CurrentYEAR = YEAR(o.date_add) = YEAR(CURRENT_DATE())
对于LastYEAR = YEAR(o.date_add) = YEAR(NOW() - INTERVAL 1 YEAR)
答案 0 :(得分:1)
我认为你可以尝试这样的事情(我为带有SUM的字段和Where条件添加CASE以仅提取相关年份):
SELECT
IFNULL(SUM( CASE WHEN YEAR(CURRENT_DATE)-YEAR(o.date_date) =0 THEN o.total_paid_tax_excl ELSE 0 END), 0) AS CurrentYEAR,
IFNULL(SUM( CASE WHEN YEAR(CURRENT_DATE)-YEAR(o.date_date) =1 THEN o.total_paid_tax_excl ELSE 0 END), 0) AS LastYEAR,
IFNULL(CONCAT(l.name), 0) AS name
FROM
expoled.ps_orders o
LEFT JOIN
expoled.ps_address a ON o.id_address_delivery = a.id_address
INNER JOIN
expoled.ps_country c ON a.id_country = c.id_country
INNER JOIN
expoled.ps_country_lang l ON c.id_country = l.id_country
WHERE
l.id_lang = 7
AND o.current_state IN (3 , 4, 5, 9, 13, 15, 20, 22, 23, 24, 25, 121)
AND l.name NOT IN ('Netherlands')
AND YEAR(o.date_date) IN (YEAR(CURRENT_DATE()), YEAR(CURRENT_DATE)-1)
GROUP BY (l.name)
答案 1 :(得分:0)
您可以在if()
聚合函数中使用条件表达式(case
函数或sum()
语句)仅添加符合条件的值:
SELECT
IFNULL(SUM(DISTINCT if(YEAR(o.date_add) = YEAR(CURRENT_DATE()),o.total_paid_tax_excl, 0)), 0) AS CurrentYEAR,
IFNULL(SUM(DISTINCT if(YEAR(o.date_add) = YEAR(CURRENT_DATE())-1,o.total_paid_tax_excl, 0)), 0) AS LastYEAR,
IFNULL(l.name, '') AS name
FROM
expoled.ps_orders o
LEFT JOIN
expoled.ps_address a ON o.id_address_delivery = a.id_address
INNER JOIN
expoled.ps_country c ON a.id_country = c.id_country
INNER JOIN
expoled.ps_country_lang l ON c.id_country = l.id_country
WHERE
l.id_lang = 7
AND o.current_state IN (3 , 4, 5, 9, 13, 15, 20, 22, 23, 24, 25, 121)
AND l.name NOT IN ('Netherlands')
GROUP BY IFNULL(l.name, '')
我还简化了name字段的表达式,并使group by
子句与它一致。
我没有更改查询的任何其他部分,但我并不真正同意distinct
中的sum()
,因为您可以获得与税相同的价值,但这是您的数据
如果您的表的数据比上一年的数据旧,那么请考虑添加where条件来限制运行计算的记录。