您能否帮助修改查询或其他查询以获得预期结果

时间:2016-06-13 07:32:17

标签: mysql sql

我尝试了很多方法,但没有得到预期的结果。我怎样才能得到预期的结果。

您可以从此处下载dbtable structure: -

SELECT 
    IF(o.source_id = 1, 'online',0)  TYPE,
        MONTH(date_created) AS monthvalue
        ,SUM(total_price) AS totalSale
FROM orders o
WHERE   o.source_id = 1  AND  date_created BETWEEN(CURDATE() - INTERVAL 1 MONTH)
    AND CURDATE()
GROUP BY monthvalue

UNION ALL

SELECT 
    IF(o.source_id = 2, 'visit',0)  TYPE,
        MONTH(date_created) AS monthvalue
        ,SUM(total_price) AS totalSale
FROM orders o
WHERE   o.source_id =2 AND  date_created BETWEEN(CURDATE() - INTERVAL 1 MONTH)
    AND CURDATE()
GROUP BY monthvalue

UNION ALL

SELECT 
    IF(o.source_id = 3, 'phone',0)  TYPE,
        MONTH(date_created) AS monthvalue
        ,SUM(total_price) AS totalSale
FROM orders o
WHERE   o.source_id = 3 AND  date_created BETWEEN(CURDATE() - INTERVAL 1 MONTH)
    AND CURDATE()
GROUP BY monthvalue

得到结果: -

TYPE    monthvalue  totalSale   
online  6            38300
visit   6            16800
phone   5              500
phone   6             7150

预期结果:

Type    May     June
online  0       38300
Visit   0       16800
Phone   500      7150

1 个答案:

答案 0 :(得分:2)

根据您的数据库架构,如果您只是想要预期的结果,请尝试按照sql;)

select 
    case source_id when 1 then 'online' when 2 then 'visit' when 3 then 'phone' end as `Type`,
    sum(if(month(date_created) = 5, total_price, 0)) as `May`,
    sum(if(month(date_created) = 6, total_price, 0)) as `June`
from `orders`
where date_created between (curdate() - interval 1 month) and curdate()
group by source_id 

SQLFiddle DEMO HERE