我正在编写一个SQL查询来计算该特定日期的用户总数
查询如下: -
select plan_date, type_name, account_type_id, new_type
FROM (
select
final_reporting_db.plan_change_facts.date as plan_date,
final_reporting_db.plan_dim.account_type as type_name,
final_reporting_db.plan_dim.id as account_type_id,
(
select count(*) as new_type from final_reporting_db.plan_change_facts
where final_reporting_db.plan_change_facts.plan_status_dim_id = account_type_id
and final_reporting_db.plan_change_facts.date = plan_date
) as new_type
FROM
final_reporting_db.plan_change_facts
INNER JOIN final_reporting_db.plan_dim where final_reporting_db.plan_dim.id in(1,2,3,4,5,6,8,9,13)
) main_table where plan_date between '2016-04-24' and '2016-04-28' group by plan_date, type_name;
在此查询子查询中花费了太多时间来执行,因为它正在计算该日期的计数。
我对如何提高此查询性能感到困惑。 因为执行需要36秒。 有没有办法使用group by子句而不是使用嵌套查询。 帮助将不胜感激
答案 0 :(得分:1)
评论太长了。
首先,您的查询几乎无法阅读。我提出的最好的是:
select cf.date as plan_date,
d.account_type as type_name, d.id as account_type_id,
(select count(*) as new_type
from final_reporting_db.plan_change_facts cf2
where cf2.plan_status_dim_id = ??.account_type_id and
cf2.date = ??.plan_date
-------------------------^ I assume this should be cf
) as new_type
from final_reporting_db.plan_change_facts cf join
final_reporting_db.plan_dim d
-----^ where is the `on` clause ???
where d.id in(1,2,3,4,5,6,8,9,13) and
cf.date between '2016-04-24' and '2016-04-28'
group by plan_date, type_name;
我观察到以下内容:
on
子句,因此这是笛卡尔积。group by
。