MySQL查询将SUM但是if语句在其他字段中

时间:2013-03-20 19:39:53

标签: mysql

我遇到mysql查询问题,我想用else if语句选择SUM,这是我的故事。

我的查询:

SELECT SUM(s.total_revenue) AS sum_revenue, m.revenue_type AS revenue_type, d.campaignid AS placement_id
FROM ox_data_summary_ad_hourly AS s
INNER JOIN ox_banners AS d ON (d.bannerid = s.ad_id) 
INNER JOIN ox_campaigns AS m ON (m.campaignid = d.campaignid) 
INNER JOIN ox_clients AS a ON (a.clientid = m.clientid) 
WHERE a.type = 0
GROUP BY placement_id
LIMIT 0 , 30

并在上面查询得到如下结果:

enter image description here

我想生成查询: 如果revenue_type = 4将更改值sum_revenue = value placement_id, 示例结果我想如下图所示:

enter image description here

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用CASE表达式来获得结果:

SELECT 
    case 
        when m.revenue_type = 4 
        then d.campaignid 
        else SUM(s.total_revenue) end AS sum_revenue, 
    m.revenue_type AS revenue_type, 
    d.campaignid AS placement_id
FROM ox_data_summary_ad_hourly AS s
INNER JOIN ox_banners AS d 
    ON (d.bannerid = s.ad_id) 
INNER JOIN ox_campaigns AS m 
    ON (m.campaignid = d.campaignid) 
INNER JOIN ox_clients AS a 
    ON (a.clientid = m.clientid) 
WHERE a.type = 0
GROUP BY placement_id
LIMIT 0 , 30

答案 1 :(得分:1)

当m.revenue_type = 4时的SELECT情况然后d.campaignid否则SUM(s.total_revenue)AS sum_revenue end,m.revenue_type AS revenue_type,d.campaignid AS placement_id 来自ox_data_summary_ad_hourly AS INNER JOIN ox_banners AS d ON(d.bannerid = s.ad_id) INNER JOIN ox_campaigns AS m ON(m.campaignid = d.campaignid) INNER JOIN ox_clients AS ON(a.clientid = m.clientid) WHERE a.type = 0 GROUP BY placement_id 限制0,30