[英]SQL - How to stitch two rows from the same table
一種方法是使用兩個從屬子查詢-但這可能不是很有效,MySql在優化從屬子查詢方面不是很聰明。
SELECT client,
date as date1,
( SELECT date FROM table t2
WHERE t1.client = t2.client
AND t2.date > t1.date
ORDER BY t2.date LIMIT 1
) as date2,
random As random1,
( SELECT random FROM table t2
WHERE t1.client = t2.client
AND t2.date > t1.date
ORDER BY t2.date LIMIT 1
) as random2
FROM table t1
您可以在table(client, date)
上創建多列索引table(client, date)
以加快此查詢的速度。
有幾種方法。 也許最簡單的方法是使用substring_index()
/ group_concat()
hack:
select client, min(date) as date1, max(date) as date2,
substring_index(group_concat(random order by date), ',', 1) as random1,
substring_index(group_concat(random order by date desc), ',', 1) as random2
from t
where date >= '2015-01-01' and
date < '2016-01-01'
group by client;
給定您的樣本數據,這應該可以正常運行。
一種更傳統的方法是使用聚合和聯接:
select c.client, c.date1, c.date2, t1.random as random1, t2.random as random2
from (select t.client, min(date) as date1, max(date) as date2
from t
where date >= '2015-01-01' and date < '2016-01-01'
group by client
) c join
t t1
on c.client = t1.client and c.date1 = t1.date join
t t2
on c.client = t2.client and c.date2 = t2.date;
這也使添加兩個以上的數據列變得更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.