sql >> Database teknologi >  >> RDS >> Mysql

Beregn kun forskellen mellem min og maks for hver kolonne, hvis den er højere end 0

Overvej følgende:

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

Seneste odds:

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:
 

Tidligste odds:

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;
 

Resultat:

+------------+---------+----------+------+-------+ | 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. Tilladelser til at oprette en trigger i mysql

  2. Oracle som løsning af muterende tabeller

  3. ORA-00001 unik begrænsning overtrådt

  4. Mysql/Php - Aktuel dato og tid