Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从每个月开始重新排列MySQL表_Mysql_Sql - Fatal编程技术网

从每个月开始重新排列MySQL表

从每个月开始重新排列MySQL表,mysql,sql,Mysql,Sql,这是我的目标表 retail_id month tgt_volume product_type 1 2013-11-01 2 Bar 2 2013-10-01 1 Touch 3 2013-09-01 1 Bar 4 2013-10-01 5 Smart 5 2013-10-01 8 Bar 3

这是我的目标表

retail_id month tgt_volume product_type 1 2013-11-01 2 Bar 2 2013-10-01 1 Touch 3 2013-09-01 1 Bar 4 2013-10-01 5 Smart 5 2013-10-01 8 Bar 3 2013-08-01 2 Smart 2 2013-08-01 5 Bar 3 2013-07-01 7 Bar 3 2013-07-01 2 Smart
您可以在聚合函数中使用
CASE
语句来实现这一点:

SELECT  Retail_ID,
        SUM(CASE WHEN product_Type = 'Bar' THEN tgt_Volume ELSE 0 END) AS Bar,
        SUM(CASE WHEN product_Type = 'smart' THEN tgt_Volume ELSE 0 END) AS Smart,
        SUM(CASE WHEN product_Type = 'Touch' THEN tgt_Volume ELSE 0 END) AS Touch,
        SUM(tgt_Volume) AS Total,
        Month
FROM    targets 
GROUP BY RetailId, Month;

谢谢。但如果我在一个普通月份插入其他零售id。它没有显示正确的数据。例如,如果我插入(2,'2013-07-01',7,'Bar'),则2013-07-01月应为2和3零售id插入2行。请查看您的again@GarethD . . . 我将您的查询更改为“按
零售Id
月进行分组”,因为我认为这就是OP所寻找的。
SELECT   DISTINCT t.retail_id,bar_vol.bar,smart_vol.smart,touch_vol.touch,total.total,t.month FROM targets t
LEFT JOIN
(SELECT SUM(tgt_volume) AS bar,retail_id FROM targets t1 WHERE t1.product_type='Bar' GROUP BY retail_id) AS bar_vol  
ON  t.retail_id=bar_vol.retail_id
LEFT JOIN
(SELECT SUM(tgt_volume) AS smart,retail_id FROM targets t2 WHERE t2.product_type='Smart' GROUP BY retail_id) AS smart_vol  
ON  t.retail_id=smart_vol.retail_id
LEFT JOIN
(SELECT SUM(tgt_volume) AS touch,retail_id FROM targets t3 WHERE t3.product_type='Touch' GROUP BY retail_id) AS touch_vol  
ON  t.retail_id=touch_vol.retail_id
LEFT JOIN
(SELECT SUM(tgt_volume) AS total,retail_id FROM targets t4  GROUP BY retail_id) AS total  
ON  t.retail_id=total.retail_id
SELECT  Retail_ID,
        SUM(CASE WHEN product_Type = 'Bar' THEN tgt_Volume ELSE 0 END) AS Bar,
        SUM(CASE WHEN product_Type = 'smart' THEN tgt_Volume ELSE 0 END) AS Smart,
        SUM(CASE WHEN product_Type = 'Touch' THEN tgt_Volume ELSE 0 END) AS Touch,
        SUM(tgt_Volume) AS Total,
        Month
FROM    targets 
GROUP BY RetailId, Month;