以下是表中的示例数据集:
| callid | called | calling | end |
|------------|--------------|-------------|---------------------|
| 1411482360 | 001143792042 | 08444599175 | 2014-07-31 13:55:03 |
| 1476992122 | 001143792042 | 08441713191 | 2014-07-31 14:05:10 |
到目前为止,我已设法获得前一行值,我还需要下一行值。这是我的疑问:
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 @prevDate = DATE_FORMAT(c.`end`,'%Y-%m-%d'), 1, 0) as Gain,
@prevCust := c.called as prevCust,
@prevComp := c.calling as prevComp,
@prevDate := DATE_FORMAT(c.`end`,'%Y-%m-%d') as prevDate
FROM cdrdata_archive c CROSS JOIN
(SELECT @prevComp := NULL, @prevCust := NULL, @prevDate := NULL) prevVals
ORDER BY c.called, c.`end`
以上查询返回以下结果集:
Customer Company Date prevCust prevComp prevDate Gain
00140443360 08434599117 2014-01-28 00140443360 08434599117 2014-01-28 0
00475172558 08434599218 2014-01-27 00475172558 08434599218 2014-01-27 0
00475172558 08434593455 2014-01-27 00475172558 08434599118 2014-01-27 1
我需要上一行和下一行值来计算每个公司的丢失和获得的呼叫。我设法获得了正确的增值,但计算Lost
值(类似于Gain
但在新列中),我需要下一个客户,公司和日期。
这可以在没有太大成本的情况下适用于此查询,还是需要重写它?
答案 0 :(得分:0)
使用MySQL LIMIT
子句进行研究。您的行将返回ORDER BY
,因此您确实有订单,但您没有“列表中的数字”,LIMIT是
所以你有了你的查询 - 并且在你追加的SQL末尾
LIMIT $x, 1
你有LIMIT <offset>, <count>
所以你的计数就是你的行(1),每当你转到'下一行'时你都会改变
$x = $x + 1
希望这会有所帮助。 http://www.mysqltutorial.org/mysql-limit.aspx
因此,您所显示类型的第三次查询将是:
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 @prevDate = DATE_FORMAT(c.`end`,'%Y-%m-%d'), 1, 0) as Gain,
@prevCust := c.called as prevCust,
@prevComp := c.calling as prevComp,
@prevDate := DATE_FORMAT(c.`end`,'%Y-%m-%d') as prevDate
FROM cdrdata_archive c CROSS JOIN
(SELECT @prevComp := NULL, @prevCust := NULL, @prevDate := NULL) prevVals
ORDER BY c.called, c.`end` LIMIT 2,1