SQL Sum布尔值并添加汇总行

时间:2019-04-18 17:33:41

标签: mysql sql

我有三个表,需要为该表提供一个带有摘要的表。还需要添加一个摘要行。

主要问题是我不知道如何使用BOOLEAN类型。 尝试使用 SUM(CASE WHEN was_showed = 'TRUE' THEN 1 ELSE 0 END),但是当我只尝试对table1进行操作时,在每种情况下都返回“ 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_showed) by all rows | sum(was_bougth)/sum(was_showed) by all rows

更新:SQL Fiddle

2 个答案:

答案 0 :(得分:2)

如果这些是tinyint,则只需将它们加起来即可。获取总数需要一些技巧:

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;

Here是一个SQL提琴。

或者您可以使用with rollup

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

答案 1 :(得分:1)

您可能需要的查询是:

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

SQL Fiddle Example