Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a possible solution. You may need to modify it to suit your needs:</p> <pre><code>DELIMITER $$ DROP PROCEDURE IF EXISTS `test`.`ordertotals` $$ CREATE PROCEDURE `test`.`ordertotals` () BEGIN DECLARE `xtab_qry` VARCHAR(4096) DEFAULT ''; SELECT CONCAT('SELECT o.product_id ', GROUP_CONCAT( DISTINCT CONCAT(', SUM(IF(o.created_at="', ol.created_at, '",o.quantity,null)) AS "', DATE_FORMAT(ol.created_at, "%m/%d/%Y"), '"') ORDER BY ol.created_at SEPARATOR '' ), ' FROM orderlines o WHERE 1 GROUP BY o.product_id' ) AS stuff INTO @xtab_qry FROM orderlines ol WHERE 1; PREPARE my_sql_statement FROM @xtab_qry; EXECUTE my_sql_statement; DEALLOCATE PREPARE my_sql_statement; END $$ DELIMITER ; </code></pre> <p>With this test data:</p> <pre><code>product_id quantity created_at 1 4 2009-09-14 1 5 2009-09-14 2 2 2009-09-14 3 3 2009-09-13 1 9 2009-09-15 1 2 2009-09-16 </code></pre> <p>It produced these results:</p> <pre><code>product_id 09/13/2009 09/14/2009 09/15/2009 09/16/2009 1 9 9 2 2 2 3 3 </code></pre> <p>Hope this helps!</p> <p>EDIT: In summary, what this does is to create a stored procedure that generates a dynamic SQL string. It then executes that query. This is why this needs to be in a stored procedure. indiecompanyllc pointed to a great article that I used a while ago to learn how to do this. Here is that link: <a href="http://rpbouman.blogspot.com/2005/10/creating-crosstabs-in-mysql.html" rel="nofollow noreferrer">http://rpbouman.blogspot.com/2005/10/creating-crosstabs-in-mysql.html</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload