[英]MySQL: Get previous row
I have the following query: 我有以下查询:
SELECT c.called as customer, c.calling as company, DATE_FORMAT(c.`end`,'%Y-%m-%d') as _date,
@G := if(@prevComp <> c.calling AND @prevCust = c.called AND @prevDay = DATE_FORMAT(c.`end`,'%Y-%m-%d'), 1, 0) as Gain,
@prevComp := c.called as prevComp,
@prevCust := c.calling as prevCust,
@prevDay := DATE_FORMAT(c.`end`,'%Y-%m-%d') as prevDate
FROM cdrdata_archive c,
(SELECT @prevComp := 0, @prevCust := 0, @prevDay := 0) prevVals
ORDER BY c.called, DATE_FORMAT(c.`end`,'%Y-%m-%d')
However this outputs the same row values for prevCust
, prevCompany
and prevDate
: 但是,这将为
prevCust
, prevCompany
和prevDate
输出相同的行值:
Customer Company Date prevCust prevComp prevDate
00140443360 08434599117 2014-01-28 00140443360 08434599117 2014-01-28
00475172558 08434599218 2014-01-27 00475172558 08434599218 2014-01-27
00475172558 08434599118 2014-01-27 00475172558 08434599118 2014-01-27
The desired output should be: 所需的输出应为:
Customer Company Date prevCust prevComp prevDate
00140443360 08834599117 2014-01-28 null null null
00475172558 08834599218 2014-01-27 00140443360 08834599117 2014-01-28
00475136333 08834098771 2014-01-22 00475172558 08834599218 2014-01-27
This is tricky, because you cannot assign the variable and pull the previous value in one statement. 这很棘手,因为您不能分配变量并在一个语句中提取前一个值。 So, the trick is to use another variable to hold the value.
因此,诀窍是使用另一个变量来保存值。
The following logic gets the previous day using case
statements and the dreaded = NULL
. 以下逻辑使用
case
语句和dreaded = NULL
获取前一天。 I use this because I know it will never be true, so the case
statement simple acts as a method of ordering the evaluation of the variables. 我之所以使用它,是因为我知道它永远不会成立,因此
case
语句简单地用作对变量求值进行排序的一种方法。
Your sample output doesn't have gain
, so I've omitted it: 您的示例输出没有
gain
,因此我省略了它:
SELECT c.called as customer, c.calling as company,
DATE_FORMAT(c.`end`,'%Y-%m-%d') as _date,
(case when (@t1 := @prevComp) = NULL then @prevComp -- never happens
when (@prevComp := c.called) = NULL then @prevComp -- never happens
else @t1
end) as prevComp,
(case when (@t2 := @prevCust) = NULL then @prevCust -- never happens
when (@prevCust := c.calling) = NULL then @prevCust -- never happens
else @t2
end) as prevCust,
(case when (@t3 := @prevDate) = NULL then @prevDate -- never happens
when (@prevCust := c.`end`) = NULL then @prevDate -- never happens
else DATE_FORMAT(@t3,'%Y-%m-%d')
end) as prevCust
FROM cdrdata_archive c CROSS JOIN
(SELECT @prevComp := NULL, @prevCust := NULL, @prevDay := NULL) prevVals
ORDER BY c.called, DATE_FORMAT(c.`end`,'%Y-%m-%d');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.