SQLITE - transposing rows into columns properly

后端 未结 1 1952
野的像风
野的像风 2021-01-18 11:11

I\'ve a database containing a table for products order like this:

order_id | prod_code | prod_color | size | quantity |  
-----------------------------------         


        
1条回答
  •  抹茶落季
    2021-01-18 11:44

    I added an extra JOIN condition: AND o.prod_color = p.prod_color

    http://sqlfiddle.com/#!5/fadad/5

    SELECT
      o.order_id, o.prod_code, o.prod_color, o.size, o.quantity,
      MAX(CASE WHEN p.currency = 'EUR' THEN p.price END) AS 'EUR',
      MAX(CASE WHEN p.currency = 'USD' THEN p.price END) AS 'USD',
      MAX(CASE WHEN p.currency = 'YEN' THEN p.price END) AS 'YEN',
      MAX(CASE WHEN p.currency = 'RUB' THEN p.price END) AS 'RUB'
    
    FROM products_order o
    JOIN products_prices p
      ON o.prod_code = p.prod_code
     AND o.prod_color = p.prod_color /* this line is added */
    
    WHERE o.order_id = '1'
    GROUP BY
      o.order_id,
      o.prod_code,
      o.prod_color,
      o.size,
      o.quantity
    

    Simplified example queries without the GROUP BY shows the difference:

    http://sqlfiddle.com/#!5/fadad/13

    0 讨论(0)
提交回复
热议问题