每月重新安排mysql表

时间:2013-12-08 18:01:22

标签: 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         2013-08-01    2        Smart
2         2013-08-01    5        Bar
3         2013-07-01    7        Bar
3         2013-07-01    2        Smart

我需要这种格式

retail_id  bar  smart   touch   total   month
1           2    0       0       2       2013-11-01
2           0    0       1       1       2013-10-01     
2           5    0       0       5       2013-08-01
3           1    0       0       1       2013-09-01 
3           0    2       0       2       2013-08-01 
3           7    2       0       9       2013-07-01
4           0    5       0       5       2013-08-01
5           8    0       0       8       2013-10-01  

因此,我想检索每个retail_id的每个月总目标和每个产品类型总计。我正在尝试一个查询,每个product_type计算一次但不计算每个月。我怎么能这样做以上格式..我的测试查询是(没有月数)

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

1 个答案:

答案 0 :(得分:1)

您可以在聚合函数中使用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;

<强> Example on SQL Fiddle