1

我在使用 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

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

在此处输入图像描述

我想生成查询:如果收入类型 = 4 将改变值 sum_revenue = 值放置_id,示例结果我想如下图所示:

在此处输入图像描述

谢谢你帮助我。

4

2 回答 2

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
于 2013-03-20T19:44:29.503 回答
1

SELECT case when m.revenue_type = 4 then d.campaignid else SUM(s.total_revenue) AS sum_revenue end, m.revenue_type ASincome_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

于 2013-03-20T19:46:27.227 回答