[英]SQL complicated query
編輯:
我的表由 id、segmentID、月、年和平均速度組成,我在這里創建了一些演示數據的 sqlfiddle: http ://sqlfiddle.com/#!2/183c1/1
我需要識別上個月平均行駛速度下降超過 10% 的路段。
有人可以幫我嗎? 謝謝
謝謝
您需要選擇每個月,加入下個月(由於您的表結構,這有點令人費解)並找到減少(/增加)。 嘗試以下復雜查詢
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
這是我的解決方案
關鍵是要跟蹤上個月和下個月之間的關系,所以我正在做 year*100+month 和 after group by year and moth 檢查 year*100+month 字段中的差異 1 和 89。 同樣遺憾的是,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;
這需要自聯接。 這個答案會讓你開始。 你可以處理細節。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.