简体   繁体   中英

Combining sql select queries

I have 2 different queries, which both return results similar to below. For example

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;

Information comes from the same table, but part of it is a different WHERE (with the date being the field which is the same in both).

Which both return information like..

value| testdate  |
+--------+-------+
| 60 | 2014-09-20|
| 57 | 2014-09-21|
| 56 | 2014-09-22|
| 55 | 2014-09-23|
| 59 | 2014-09-24|

What I would like to do, is combine both sets of results into one (and then perform some maths like a ratio on the two numbers), so I want to end up with something like...

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 |

I'm guessing I need a JOIN somewhere, but can't figure it, and how to use that value for some basic maths in there ?

You should use the " Self Join " to join the 2 instances of same table. like below

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;

I would recommend conditional aggregation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM