Add a New Column with ALIASES on 'date' by automation based on search results
-
31-12-2020 - |
سؤال
I am trying to create a new column based on date search result.
I have written a code in the link SQL fiddle as I am looking for date automation on each column based on the date format. the date format Coloum can be up to 7 column or less or more, just based on how many dates in the record.
Here is a screenshot as I would like to get this similar and the data is based on the number of sold SKU.
المحلول
Update status:-
As got advice and helpful from @ypercube
so far I got sorted with Fix static Pivot table but not dynamic Pivot table,
Here is a Static pivot table
SELECT
ls.sku AS list_sku,
COALESCE( MIN(suo.sku), 'Not Sold' ) AS sold_sku,
SUM(CASE suo.date WHEN '2018-04-30' THEN units_ordered ELSE 0 END) AS Monday,
SUM(CASE suo.date WHEN '2018-05-01' THEN units_ordered ELSE 0 END) AS Tuesday,
SUM(CASE suo.date WHEN '2018-05-02' THEN units_ordered ELSE 0 END) AS Wednesday,
SUM(CASE suo.date WHEN '2018-05-03' THEN units_ordered ELSE 0 END) AS Thursday,
COALESCE( SUM(suo.units_ordered), 0 ) AS total_sold
FROM tbl_list_sku AS ls
LEFT JOIN tbl_sku_units_order AS suo
ON suo.sku = ls.sku
GROUP BY ls.sku
ORDER BY total_sold DESC ;
Here is output results
So far I will update this answers when I got a fix with Dynamic table
Update: Got fix with Dynamic Pivot Table and please with it
SET
@sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT( 'MAX(IF(suo.date = ''', date, ''', suo.units_ordered, 0)) AS ', CONCAT("`", date, "`") ) ) INTO @sql
FROM
tbl_sku_units_order;
SET
@sql = CONCAT('SELECT ls.sku AS "List SKU",
COALESCE( MIN(suo.sku), "Not Sold" ) AS "sold_sku", ', @sql, ' , COALESCE( SUM(suo.units_ordered), 0 ) AS total_sold
FROM
tbl_list_sku AS ls
LEFT JOIN
tbl_sku_units_order AS suo
ON suo.sku = ls.sku
GROUP BY
ls.sku
ORDER BY
total_sold DESC');
PREPARE stmt
FROM
@sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Here is a result
I know I'm not great code in the world, but delight with results and thank for your help @ypercube.