在下面的查询中,它带来每个主类别中的广告计数。我还希望再增加一列,以显示所有广告的数量(无论哪个主类别,所有广告的总和)。我需要在下面的查询中带来什么变化?
谢谢
select count(*),master_category,count(a2.adid) from ad a1
inner join Category c on a1.catid=c.id
inner join ad a2 on a1.adid=a2.adid
group by c.master_category
答案 0 :(得分:1)
如果您想添加一列总计数,则可以在按类别分类的结果和总计数之间使用交叉联接
select t1.master_category, t1.count_by_cat, t2.tot_count
from (
select master_category,count(a2.adid) count_by_cat
from ad a1
inner join Category c on a1.catid=c.id
inner join ad a2 on a1.adid=a2.adid
group by c.master_category )
) t1
cross join (
select count(*) tot_count
inner join Category c on a1.catid=c.id
inner join ad a2 on a1.adid=a2.adid
) t2
交叉联接是两组行之间的笛卡尔乘积..在这种情况下,一组用于类别结果,第二组仅用于类别结果
然后将交叉连接与总结果一起使用允许为每一行显示相同的结果..(在这种情况下,由第二个子查询计算出的总值)
通常是类别的每一行的结果与单个值
答案 1 :(得分:0)
尝试这样的事情:
select c.master_category,
count(a1.adid) as countGroup,
min(a2.count1) as countAll
from ad a1
inner join Category c on a1.catid=c.id
left join (select count(ad.someColumn) as count1 from ad) as a2 on a2.adid = a1.adai
group by c.master_category
答案 2 :(得分:0)
使用窗口功能:
select c.master_category, count(*) as category_cnt,
sum(count(*)) over () as total_cnt
from ad a inner join
Category c
on a.catid = c.id
group by c.master_category;
我不明白您为什么两次加入ad
。这不仅是最简单的方法,而且应该具有您想要执行的最佳性能。
答案 3 :(得分:0)
我只是修改您的查询,希望对您有帮助
select count(
select * from ad a1
inner join Category c on a1.catid=c.id
inner join ad a2 on a1.adid=a2.adid) as Total,master_category,count(a2.adid) from ad a1
inner join Category c on a1.catid=c.id
inner join ad a2 on a1.adid=a2.adid
group by c.master_category