假设我有一个如下所示的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“,mobile,200),供应商”ABC“("ABC",平板电脑,300)。
我的目标是做到这一点,并找到两者的总和,并将其放在一个名为“all”的平台中。
我尝试通过添加一个额外的情况来使用相同的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,或者是否需要通过对原始SQL结果进行选择来进行更高级别的聚合?
谢谢。
更新:
它是MYsql (关系数据库管理系统),是的,我需要一个值'all‘的单独行(这将包含'mobile’和'tablet‘的点击和。
例如:("ABC",手机,200),("ABC",平板电脑,300),("ABC",全部,500)
发布于 2014-01-07 20:51:04
如果你想要的结果
supplier platform clicks
abc tablet 12
abc mobile 34将case语句添加到组中
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发布于 2014-01-07 20:38:11
问题是,您的最后一个WHEN标准永远不会满足,因为前两个标准中的一个总是首先满足的。您要么需要一个单独的CASE语句,要么需要一个条件SUM(),如下所示:
SUM(CASE WHEN platform in (5,6,7,8) THEN 1 END)此外,您应该有任何非聚合值,包括CASE语句在GROUP BY子句中,即使mySQL没有在不完整的GROUP BY子句上出错。
https://stackoverflow.com/questions/20981318
复制相似问题