使用mysql减去每个客户今年销售额的去年销售额(每年更多条目[总和])

时间:2017-01-19 09:06:41

标签: mysql

就像已经写在标题中一样,我首先将每个客户的所有销售额加上去年今年,然后从去年开始减去{{1} }为每个客户。

修改:

(last year - this year)



所以去年安娜的成绩应该是400,而今年600。差异应该是200。

我已经尝试了一些查询但对我来说太复杂了:


   clientid | ....date..... | quant    | product. | client | place    | price | 
 ......1... |2016-01-10     | ...1.... | product1 | anna   | Italy... | .100. | 
 ......1... |2016-04-12     | ...2.... | product2 | anna   | Italy... | .300. | 
 ......1... |2017-01-10     | ...1.... | product1 | anna   | Italy... | .200. | 
 ......1... |2017-04-12     | ...2.... | product1 | anna   | Italy... | .400. | 

2 个答案:

答案 0 :(得分:0)

可能你可以试试这个。在一个子查询中,我将当前年份的总和和另一个子查询取上一年的总和,并使用两者来得到不同的。

Select m1.clientid, m1.cyear, m0.pyear, m1.sum csum, m0.sum psum, ( m1.sum - m0.sum ) diff from ( select clientid, cyear, sum from ( select clientid, year(date) cyear, sum(price) sum from buget group by clientid, cyear ) T where cyear = year(curdate()) ) m1, ( ( select clientid, pyear, sum from ( select clientid, year(date) pyear, sum(price) sum from buget group by clientid, pyear ) T where pyear = ( year(curdate()) ) - 1) m0 ) where m1.clientid = m0.clientid

答案 1 :(得分:0)

更新了答案

select ABS(t3.price2 - t2.price1),t1.client from buget t1 inner join (select sum(price) as price1 from buget where year(date) = year(now()) group by client) t2 on year(date) = year(now()) inner join (select sum(price) as price2 from buget where year(date) = year(now()) - 1 group by client) t3 group by client;