编辑:
我的表格由id,segmentID,月份,年份和平均速度组成, 我在这里创建了一些带有一些演示数据的sqlfiddle:http://sqlfiddle.com/#!2/183c1/1
我需要确定平均驾驶速度在过去一个月内下降超过10%的细分市场。
有人可以帮我吗? 感谢
由于
答案 0 :(得分:1)
您需要选择每个月,加入下个月(由于您的表结构而有点复杂)并找到减少(/增加)。请尝试以下复杂查询
SELECT
t1.segmentID, t1.month, t1.year, AVG(t1.avgSpeed) as avgSpeed1,
AVG(t2.avgSpeed) as avgSpeed2,
1-(AVG(t1.avgSpeed)/AVG(t2.avgSpeed)) as decrease
FROM
travels t1
LEFT JOIN
travels t2
ON
CONCAT(t2.year,'-',LPAD(t2.month,2,'00'),'-',LPAD(1,2,'00')) = DATE_ADD(CONCAT(t1.year,'-',LPAD(t1.month,2,'00'),'-',LPAD(1,2,'00')), INTERVAL -1 MONTH)
GROUP BY
segmentID, month, year
HAVING
avgSpeed1/avgSpeed2 < .9
这是更新后的SQLFiddle - http://sqlfiddle.com/#!2/183c1/25
答案 1 :(得分:1)
这是我的解决方案
关键是要记录上个月和下一个月之间,所以我做了一年* 100 +月和一年又一年,并且检查差异1和89年* 100 +月场。 另外,MySQL不支持CTE并使用派生表使查询变得丑陋也很可怜。
代码:
select s.month,s.speed,m.month as prevmonth,m.speed as sp, 100-s.speed/m.speed*100 as speeddiff from
(SELECT segmentid,month,year*100+month as mark,avg(avgSpeed) as speed from travels
group by segmentid,month,year*100+month
) as s
,
(SELECT segmentid,month,year*100+month as mark,avg(avgSpeed) as speed from travels
group by segmentid,month,year*100+month
) as m
where s.segmentid=m.segmentid and (s.mark=m.mark+1 or s.mark=m.mark+89) and (m.speed-(m.speed/10))>s.speed;
CTE代码处理除MySQL以外的每个数据库
with t as(SELECT segmentid,month,year*100+month as mark,avg(avgSpeed) as speed from travels
group by segmentid,month,year*100+month
)
select s.month,s.speed,m.month as prevmonth,m.speed as sp, 100-s.speed/m.speed*100 as speeddiff from t s
inner join t m on s.segmentid=m.segmentid and (s.mark=m.mark+1 or s.mark=m.mark+89)
where (m.speed-(m.speed/10))>s.speed;
答案 2 :(得分:0)
这需要自我加入。这个答案将帮助您入门。你可以处理细节。
select somefields
from yourtable t1 join yourtable t2 on t1.something = t2.something
where t1.month = whatever
and t2.month = t1.month + 1
and t2.speed <= t1.speed * .9