[英]Combining sql select queries
我有2個不同的查詢,它們都返回類似於下面的結果。 例如
SELECT value
, date_format( statdate, "%Y-%m-%d" ) AS testdate
FROM stats
WHERE name LIKE 'myname1'
AND date >= "2014-09-20"
and date < "2014-09-24"
GROUP BY 2;
SELECT value
, date_format( statdate, "%Y-%m-%d" ) AS testdate
FROM stats
WHERE name LIKE 'myname2'
AND date >= "2014-09-20"
and date < "2014-09-24"
GROUP BY 2;
信息來自同一張表,但部分信息來自不同的WHERE(日期是字段,兩者均相同)。
兩者都返回類似的信息。
value| testdate |
+--------+-------+
| 60 | 2014-09-20|
| 57 | 2014-09-21|
| 56 | 2014-09-22|
| 55 | 2014-09-23|
| 59 | 2014-09-24|
我想做的是將兩組結果組合為一個(然后對兩個數字進行比率等數學運算),所以我想得到類似...
val1 | val2| ratio (val1/val2) | testdate |
+----+-------------------------|------------+
| 60 | 140 | 0.42 | 2014-09-20 |
| 57 | 180 | 0.31 | 2014-09-21 |
| 56 | 190 | 0.29 | 2014-09-22 |
| 55 | 10 | 5.5 | 2014-09-23 |
| 59 | 100 | 0.59 | 2014-09-24 |
我猜我需要在某個地方JOIN
一個JOIN
,但無法弄清楚,以及如何在其中使用此值進行一些基本數學JOIN
?
您應該使用“ Self Join ”來聯接同一表的2個實例。 像下面
SELECT s1.value, date_format( s1.statdate, "%Y-%m-%d" ) AS testdate
s2.value, date_format( s2.statdate, "%Y-%m-%d" ) AS testdate2,
(s1.value/s2.value) as ration
FROM stats s1, stats s2
WHERE s1.id = s2.id
and s1.name LIKE 'myname1' AND s1.date >= "2014-09-20" and s1.date < "2014-09-24"
and s2.name LIKE 'myname2' AND s2.date >= "2014-09-20" and s2.date < "2014-09-24"
GROUP BY 2;
我建議條件聚合:
SELECT date_format(statdate, '%Y-%m-%d') AS testdate,
max(case when name = 'myname1' then value end) as val1,
max(case when name = 'myname2' then value end) as val2,
(max(case when name = 'myname1' then value end) /
max(case when name = 'myname2' then value end)
) as ratio,
FROM stats
WHERE name in ('myname1', 'myname2') AND date >= '2014-09-20' and date < '2014-09-24'
GROUP BY date_format(statdate, '%Y-%m-%d');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.