sql >> Database >  >> RDS >> Mysql

SQL:zet rijen om in kolommen in MySQL (SELECT statement)

U kunt variabelen gebruiken voor dit type spil, maar de query is iets gecompliceerder, omdat u de waarden voor elke bestelling moet opsommen:

SELECT o.order_id,
       MAX(case when rank = 1 then created_at end) as created_at_1,
       MAX(case when rank = 1 then email end) as email_1,
       MAX(case when rank = 1 then content end) as content_1,
       MAX(case when rank = 2 then created_at end) as created_at_2,
       MAX(case when rank = 2 then email end) as email_2,
       MAX(case when rank = 2 then content end) as content_2,
FROM orders o LEFT JOIN
     (SELECT oc.*,
             (@rn := if(@o = order_fk, @rn + 1,
                        if(@o := order_fk, 1, 1)
                       )
             ) as rank
      FROM order_comments oc CROSS JOIN
           (SELECT @rn := 0, @o := 0) vars
      ORDER BY order_fk, created_at
     ) oc
     ON o.order_id = oc.order_fk
GROUP BY o.order_id;



  1. mysql dupliceert met LOAD DATA INFILE

  2. Hoe repareert deze website de codering?

  3. Excel VBA verbinden met Oracle DB met 'ODBC'

  4. MySQL - MINST en GROOTSTE vergelijkingsoperators