我有如下所示的SQL:
select
count(*), sum(summary.imp), sum(summary.taps)
from(
select
sum(impressions) as imp, sum(taps) as taps
from report
where org_id = 1 and report_date between '2019-01-01' and '2019-10-10'
group by org_id, country, text)
summary;
此查询在MYSQL中创建派生的临时表。有其他解决方法吗?
答案 0 :(得分:2)
我已阅读(但尚未测试)MySQL支持多个列,但计数却不同:
select
count(distinct org_id, country, text), sum(impressions) as imp, sum(taps) as taps
from report
where org_id = 1 and report_date between '2019-01-01' and '2019-10-10'
我想知道这是真的。我也相当有信心这样的事情会起作用:
select
count(distinct concat_ws('###', org_id, country, text)), sum(impressions) as imp, sum(taps) as taps
from report
where org_id = 1 and report_date between '2019-01-01' and '2019-10-10'
答案 1 :(得分:1)
您可以在由org_id
,country
和text
组成的自定义字符串上使用&&
。这样可以确保仅计算它们的唯一组合(从而模拟GROUP BY,然后模拟COUNT)。
我使用了任意定界符text
。如果您的country
或select
COUNT(DISTINCT CONCAT(org_id, '&&', country, '&&', text)),
sum(impressions) as imp,
sum(taps) as taps
from report
where org_id = 1 and report_date between '2019-01-01' and '2019-10-10'
列可以包含此分隔符,则可以使用其他一些不常见的字符组合作为分隔符:
report
为了获得良好的性能,请在(org_id, report_date)
表上定义以下组合索引:Worker.class