Mysql SQL求布尔值和并添加摘要行
我有三个表,需要得到一个类别的摘要。还需要添加一个摘要行 主要问题是我不知道如何使用布尔类型。 试用Mysql SQL求布尔值和并添加摘要行,mysql,sql,Mysql,Sql,我有三个表,需要得到一个类别的摘要。还需要添加一个摘要行 主要问题是我不知道如何使用布尔类型。 试用 SUM(CASE WHEN was_show='TRUE'然后是1 ELSE 0 END)但当我仅为表1尝试时,它在每种情况下都返回“3”…确切的时间应该是“6” 第一表1 id was_showed 1 FALSE 2 TRUE 3 TRUE 4 TRUE 5 TRUE 6 FALSE 7 TRUE 8 TRUE 9 TRUE 第二表2 id cate
SUM(CASE WHEN was_show='TRUE'然后是1 ELSE 0 END)
但当我仅为表1尝试时,它在每种情况下都返回“3”…确切的时间应该是“6”
第一表1
id was_showed
1 FALSE
2 TRUE
3 TRUE
4 TRUE
5 TRUE
6 FALSE
7 TRUE
8 TRUE
9 TRUE
第二表2
id category
1 test1
2 test2
3 test1
4 test1
5 (null)
6 (null)
7 test1
8 test2
9 test2
第三表3
id was_bought
2 TRUE
4 TRUE
5 TRUE
7 TRUE
我希望按类别获得的结果:
category | sum(was_showed) | sum(was_bougth)/sum(was_showed)
test1 | 3 | 2/3
test2 | 2 | 1/3
NULL | 1 | 1
最后一行应为:
all | sum(was_show)by all rows | sum(was_bouth)/sum(was_show)by all rows
更新:您可能需要的查询是:
select
*,
1.0 * bought / shown
from (
select
c.category,
sum(case when s.was_showed = 1 then 1 end) as shown,
sum(case when b.was_bought = 1 then 1 end) as bought
from adShowCategoryTable c -- categories
left join adShowsTable s on s.id = c.id -- shown (showed?)
left join adClicksTable b on b.id = c.id -- bought
group by c.category
) x
order by category
如果这些是微小的,你可以把它们加起来。获得总数需要一些技巧:
select coalesce(x.category, c.category) as category,
sum(s.was_showed) as shown,
sum(b.was_bought) as was_bought,
sum(b.was_bought) / sum(s.was_showed)
from table2 c left join-- categories
table1 s
on s.id = c.id left join -- shown (showed?)
table3 b
on b.id = c.id cross join
(select null as category union all
select 'total' as category
) x
group by coalesce(x.category, c.category)
order by (x.category is null) desc, c.category;
这是一个SQL小提琴
或者您可以将与汇总一起使用
:
select c.category,
sum(s.was_showed) as shown,
sum(b.was_bought) as was_bought,
sum(b.was_bought) / sum(s.was_showed)
from table2 c left join-- categories
table1 s
on s.id = c.id left join -- shown (showed?)
table3 b
on b.id = c.id
group by c.category with rollup;
这是我用SQL Fiddle创建的。@GordonLinoff,它与布尔类型一起工作…@GordonLinoff我读到布尔和布尔是TINYINT的等价物(1)小提琴在哪里?@他们的同事认为这是不允许的。当然哦,关键很简单,我应该用“1”而不是“真”。。。非常感谢,你保存了我的夜晚,为什么要使用
SUM
当你可以过滤出真实的记录,而只是COUNT
它们呢?@Hytpo-MySQL没有真正的布尔类型。它只是数字类型TINYINT
(一个字节)的同义词。谢谢,遗憾的是,加上汇总,总数也是空的。但我很感激第一个!