假设我有一个如下所示的SQL语句:
select supplier, case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end as platform,
count(*) as clicks
from supplier_table
group by supplier, platform;
这为我提供了不同平台每个供应商收到的点击细分 例如:供应商“ABC”的[(“ABC”,手机,200),(“ABC”,平板电脑,300)]
我的目标是这样做,加上找到两次点击的总和,并将其放入一个名为“全部”的平台中。
我尝试通过添加一个额外的案例来使用相同的SQL语句。
select supplier, case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' when platform in (5,6,7,8) then 'all'
end as platform,
count(*) as clicks
from supplier_table
group by supplier, platform;
但这不起作用,并且在没有“全部”平台的情况下给出了与上述相同的结果。是否可以使用Case When语句,或者我是否需要通过选择原始SQL结果来进行上层聚合?
感谢。
更新
这是MYsql(RDBMS),是的,我需要一个值为'all'的单独行(这将包含'mobile'和'tablet'的点击总和。
例如:例如:[(“ABC”,手机,200),(“ABC”,平板电脑,300),(“ABC”,全部,500)]
答案 0 :(得分:4)
如果你想要
这样的结果supplier platform clicks
abc tablet 12
abc mobile 34
将您的案例陈述添加到GROUP BY
select supplier, case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end as platform,
count(*) as clicks
from supplier_table
group by supplier,case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end
或者,如果你想要这样的结果:
supplier tablet_clicks mobile_clicks total_clicks
abc 12 34 46
你可以将你的案例分成1的总和,就像条件计数一样:
select supplier, sum(case when platform in (5,6) then 1 end) as mobile_clicks,
sum(case when platform in (7,8) then 1 end) as tablet_clicks,
count(1) total_clicks
from supplier_table
group by supplier
在看到您的更新后,如果您想要
之类的结果supplier platform clicks total_clicks
abc tablet 12 46
abc mobile 34 46
你需要使用像这样的子查询
select supplier, case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end as platform,
count(*) as clicks,
(select count(1) from supplier_table as x where x.supplier=supplier_table.supplier where x.platform in (5,6,7,8)) as total_clicks
from supplier_table
group by supplier,case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end
如果你想要
这样的结果supplier platform clicks
abc tablet 12
abc mobile 34
abc all 46
你确实使用了一个单独的非隔离查询的UNION
select supplier, case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end as platform,
count(*) as clicks
from supplier_table
group by supplier,case when platform in (5,6) then 'mobile'
when platform in (7,8) then 'tablet' end
UNION ALL
select supplier,'all',count(1) from supplier_table
where platform in (5,6,7,8)
group by supplier
答案 1 :(得分:0)
问题在于,您的上一个WHEN
条件永远不会被满足,因为前两个标准中的一个将始终首先被满足。您需要单独的CASE
语句,或者可能需要条件SUM()
,例如:
SUM(CASE WHEN platform in (5,6,7,8) THEN 1 END)
此外,您应该拥有任何非聚合值,包括CASE
子句中的GROUP BY
语句,即使mySQL没有在不完整的GROUP BY
子句中出错。