Mysql
根據搜尋結果通過自動化在“日期”上添加一個帶有別名的新列
我正在嘗試根據日期搜尋結果創建一個新列。
我在連結 SQL fiddle 中編寫了一個程式碼,因為我正在根據日期格式在每一列上尋找日期自動化。日期格式 Coloum 最多可以為 7 列或更少或更多,這取決於記錄中有多少個日期。
這是一個螢幕截圖,因為我想獲得類似的數據,數據基於已售 SKU 的數量。
更新狀態:-
從@ypercube 得到建議和幫助
到目前為止,我使用修復靜態數據透視表而不是動態數據透視表進行了排序,
這是一個靜態數據透視表
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 ;
這是輸出結果
到目前為止,當我得到動態表的修復時,我會更新這個答案
**更新:**使用動態數據透視表修復並請使用它
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;
這是一個結果
我知道我在世界上不是很棒的程式碼,但對結果感到高興並感謝@ypercube 的幫助。