结合sql select查询

时间:2014-09-25 11:45:11

标签: mysql

我有两个不同的查询,它们都返回类似于下面的结果。例如

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,但无法解决这个问题,以及如何将该值用于那里的一些基本数学?

2 个答案:

答案 0 :(得分:1)

您应该使用“自我加入”来加入同一个表的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;

答案 1 :(得分:1)

我建议使用条件聚合:

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');