简体   繁体   中英

Mysql.. how to combine these 3 requests in a single request?

To get my final table, I have to do 3 table creation to get the result..how to combine these 3 requests in a single request?

DROP TABLE IF EXISTS pturf1.scoring_chev_1;
CREATE TABLE scoring_chev_1 AS 
SELECT comp, jour, idche, cheval, cl, 
sum(case when `cl` = '1er' then 1 else 0 end)/count(*) as Top_1, 
sum(case when `cl` = '2e' then 1 else 0 end)/count(*) as Top_2,
sum(case when `cl` = '3e' then 1 else 0 end)/count(*) as Top_3,
FROM pturf1.cachedate
WHERE (typec ="plat"
AND    jour BETWEEN "2019-08-01" AND "2020-10-01")
GROUP BY comp, idche;

DROP TABLE IF EXISTS pturf1.scoring_chev_2;
CREATE TABLE scoring_chev_2 AS
SELECT idChe, cheval, (Top_1+Top_2+Top_3)AS total_che
FROM pturf1.scoring_chev_1;

DROP TABLE IF EXISTS pturf1.scoring_cheval;
CREATE TABLE scoring_cheval AS
SELECT idChe, cheval, SUM(total_che) AS total_chev
FROM pturf1.scoring_chev_2
GROUP BY idChe;

how to combine these 3 requests in a single request?

Use the SELECT queries as subqueries instead of creating tables.

CREATE TABLE scoring_cheval AS
SELECT idChe, cheval, SUM(total_che) AS total_chev
FROM (
    SELECT idChe, cheval, (Top_1+Top_2+Top_3)AS total_che
    FROM 
    (
        SELECT comp, jour, idche, cheval, cl, 
        sum(case when `cl` = '1er' then 1 else 0 end)/count(*) as Top_1, 
        sum(case when `cl` = '2e' then 1 else 0 end)/count(*) as Top_2,
        sum(case when `cl` = '3e' then 1 else 0 end)/count(*) as Top_3
        FROM pturf1.cachedate
        WHERE (typec ="plat"
        AND    jour BETWEEN "2019-08-01" AND "2020-10-01")
        GROUP BY comp, idche
    ) AS scoring_chev_1
) AS scoring_chev_2
GROUP BY idChe;

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