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

spojit dvě tabulky bez ztráty relevantních hodnot

Myslím, že hledáte toto:

select distinct *
from (SELECT date,
             if(group_concat(distinct cust_price), from_product_id, null)as from_product_id,
             if(group_concat(distinct comp_price), to_product_id, null)  as to_product_id,
             group_concat(distinct cust_price)                           as cust_price,
             group_concat(distinct comp_price)                           as comp_price
      FROM (select cust_hist.date,matches.from_product_id,
                   matches.to_product_id,cust_hist.price cust_price,
                   comp_hist.price                       comp_price
            from tmp_match matches
                   inner join tmp_price_history cust_hist on matches.from_product_id = cust_hist.product_id
                   inner join tmp_price_history comp_hist on matches.to_product_id = comp_hist.product_id
            WHERE comp_hist.date = cust_hist.date
            union
            select comp_hist.date,matches.from_product_id,
                   matches.to_product_id,null as cust_price,
                   comp_hist.price               comp_price
            from tmp_price_history comp_hist
                   join tmp_match matches
                     on matches.to_product_id = comp_hist.product_id # and matches.from_product_id is null

            union
            select cust_hist.date,matches.from_product_id,
                   matches.to_product_id,
                   cust_hist.price cust_price,
                   null            comp_price
            from tmp_price_history cust_hist
                   join tmp_match matches
                     on matches.from_product_id = cust_hist.product_id # and matches.to_product_id is null

            order by DATE, from_product_id, to_product_id, cust_price, comp_price) as u
      group by date,from_product_id,to_product_id) g

Vaše představa o úryvku SQL byla skvělá!




  1. Transponujte řádky do sloupců na základě sloupce ID

  2. Škálovatelné procesory Intel Xeon a SQL Server 2017

  3. Celý proces obnovení databáze SQL Server z příkazového řádku

  4. Postgres LIKE s hodnotou sloupce jako podřetězcem