[英]mysql group results to single table row
我有這個查詢,它返回一個度假村(res_id)未來三天的最高溫度(temphi位於t0,t1,t2)。 我希望每個度假村(對於多個度假村)連續進行一次預測。 我怎樣才能做到這一點?
查詢結果
res_id lud temphi
1 2017-02-05 -5
1 2017-02-06 -2
1 2017-02-07 -8
4 2017-02-05 2
4 2017-02-06 1
4 2017-02-07 -1
理想的結果
res_id t0 t1 t2
1 -5 -2 -8
4 2 1 -1
$rQuery1 = "SELECT a.lud, a.temphi,a.res_id
FROM sv_snowalert a
LEFT JOIN sv_orte b ON a.res_id = b.res_id AND b.ski_id>0
INNER JOIN sv_canton c ON b.can_id = c.can_id
INNER JOIN sv_country d ON c.cou_id = d.cou_id
WHERE a.lud>='2017-02-05' GROUP BY a.res_id, a.lud ORDER BY a.res_id, a.lud ASC";
$rResult1 = mysql_query($rQuery1);
$seq=0;
$num_rows = mysql_num_rows($rResult1)
while ($rows1 = mysql_fetch_array($rResult1))
{
$seq++;
// output
}
這里只是一個mysql提示:
select
a.res_id,
max(case when date(a.lud) = date_add(curdate(), interval 0 day) then temphi else null end) as t0,
max(case when date(a.lud) = date_add(curdate(), interval 1 day) then temphi else null end) as t1,
max(case when date(a.lud) = date_add(curdate(), interval 2 day) then temphi else null end) as t2
from sv_snowalert a
left join sv_orte b on a.res_id = b.res_id and b.ski_id > 0
inner join sv_canton c on b.can_id = c.can_id
inner join sv_country d on c.cou_id = d.cou_id
where a.lud between curdate() and date_add(curdate(), interval 2 day)
group by a.res_id
order by a.res_id asc
還有一個演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.