SQL查询后,如何获取两条记录之间的差异?

时间:2015-10-19 20:46:06

标签: mysql

我希望在查询后获得两条记录之间的区别。

这是查询:

select count(t.customerid) as NumberofCustomers, st.regionid, v.vendorid
from region r join store st
on r.regionid = st.regionid
join salestransaction t 
on st.storeid = t.storeid
join soldvia s
on t.tid = s.tid
join product p
on s.productid = p.productid
join vendor v
on p.vendorid = v.vendorid
where v.vendorid = 2
group by st.regionid, v.vendorid

这是查询产生的内容:

NumberofCustomers   regionid    vendorid
     495               1            2
     329               2            2

我怎样才能得到row1和row2中NumberofCustomers之间的区别? 我试图使用差异实现这一点,但它没有给我想要的结果。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

你的目标很奇怪。但是我有一个有趣而奇怪的解决方案:

SELECT t.*,
   IF(@prev IS NULL, t.NumberofCustomers, (t.NumberofCustomers- @prev)) difference,
   @prev := t.NumberofCustomers
FROM )
select count(t.customerid) as NumberofCustomers, 
   st.regionid, v.vendorid
from region r join store st
on r.regionid = st.regionid
join salestransaction t 
on st.storeid = t.storeid
join soldvia s
on t.tid = s.tid
join product p
on s.productid = p.productid
join vendor v
on p.vendorid = v.vendorid
where v.vendorid = 2
group by st.regionid, v.vendorid ) t

答案 1 :(得分:0)

如果您只有两个区域,则可以使用条件聚合:

select v.vendorid,
       sum(st.regionid = 1) as NumRegion1,
       sum(st.regionid = 2) as NumRegion2,
       (sum(st.regionid = 1) - sum(st.regionid = 2)) as diff
from region r join
     store st
     on r.regionid = st.regionid join
     salestransaction t 
     on st.storeid = t.storeid join
     soldvia s
     on t.tid = s.tid join
     product p
     on s.productid = p.productid join
     vendor v
     on p.vendorid = v.vendorid
where v.vendorid = 2
group by v.vendorid;

将数字全部返回一行,而不是两行。