sql >> Databáze >  >> RDS >> Mysql

Rozdíl mezi minimem a maximem pro každý sloupec vypočítejte, pouze pokud je vyšší než 0

Zvažte následující:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table 
(fixture_id INT NOT NULL
,updated INT NOT NULL
,outcome ENUM('Home win','Draw','Away win') NOT NULL
,odds DECIMAL(5,2) NOT NULL
,PRIMARY KEY(fixture_id,outcome,updated)
);

INSERT INTO my_table VALUES
(120,12,'Home win',1.40),
(120,11,'Home win',1.10),
(120,10,'Home win',1.20),
(120,12,'Draw',1.50),
(120,11,'Draw',1.10),
(120,12,'Away win',1.30),
(120,11,'Away win',1.10),
(120,10,'Away win',1.60);    

Poslední kurz:

SELECT x.*
  FROM my_table x
  JOIN
     ( SELECT fixture_id
            , outcome
            , MAX(updated) min_updated
         FROM my_table x
        GROUP 
           BY fixture_id
            , outcome
     ) y
    ON y.fixture_id = x.fixture_id
   AND y.outcome = x.outcome
   AND y.min_updated = x.updated;
   Earliest odds:

Nejčasnější kurz:

SELECT x.*
  FROM my_table x
  JOIN
     ( SELECT fixture_id
            , outcome
            , MIN(updated) min_updated
         FROM my_table x
        GROUP 
           BY fixture_id
            , outcome
     ) y
    ON y.fixture_id = x.fixture_id
   AND y.outcome = x.outcome
   AND y.min_updated = x.updated;

Delta:

SELECT a.*
     , a.odds - b.odds delta
  FROM 
     ( SELECT x.*
         FROM my_table x
         JOIN
            ( SELECT fixture_id
                   , outcome
                   , MAX(updated) min_updated
                FROM my_table x
               GROUP 
                  BY fixture_id
                   , outcome
            ) y
           ON y.fixture_id = x.fixture_id
          AND y.outcome = x.outcome
          AND y.min_updated = x.updated
     ) a
 JOIN
    ( SELECT x.*
         FROM my_table x
         JOIN
            ( SELECT fixture_id
                   , outcome
                   , MIN(updated) min_updated
                FROM my_table x
               GROUP 
                  BY fixture_id
                   , outcome
            ) y
           ON y.fixture_id = x.fixture_id
          AND y.outcome = x.outcome
          AND y.min_updated = x.updated
    ) b
   ON b.fixture_id = a.fixture_id
  AND b.outcome = a.outcome;

Výsledek:

    +------------+---------+----------+------+-------+
    | fixture_id | updated | outcome  | odds | delta |
    +------------+---------+----------+------+-------+
    |        120 |      12 | Home win | 1.40 |  0.20 |
    |        120 |      12 | Draw     | 1.50 |  0.40 |
    |        120 |      12 | Away win | 1.30 | -0.30 |
    +------------+---------+----------+------+-------+


  1. Potřebné rady ohledně struktury databáze

  2. Zástupný znak MySQL pro =- existuje

  3. Oracle:Jak převedu hex na desítkové v Oracle SQL?

  4. aktualizovat více řádků pomocí limitu v mysql?