希望我能从这个论坛上获得帮助,任何建议都值得赞赏。
我有一个项目,其中包含一些现有的sql查询,出于性能优化的目的,我认为应将这三个项目合并为一个。
为简便起见,下面是经过修改的代码:
table1
内部联接table2
和左联接table22
生成temp
表temp
表创建表cnt
,其中包含每种类型的计数table1
内部联接table3
,并应用where
子句以生成最终表
。 更新:此处的关键点是寻找一种解决方案,以最小化此处涉及的初始数据量(table1
)-从添加的where
子句开始,该数据有80亿行最后,它应该能够被限制在where
子句中,这将大大减小其大小。
UPDATE2:原始查询实际上在此处包括另一个左连接,请参见以下评论:
create table table1 (id int, region int, typeid int)
insert into table1 (id, region, typeid ) values (1,2,1)
insert into table1 (id, region, typeid ) values (2,3,1)
insert into table1 (id, region, typeid ) values (3,4,2)
insert into table1 (id, region, typeid ) values (4,1,2)
insert into table1 (id, region, typeid ) values (5,1,2)
insert into table1 (id, region, typeid ) values (6,2,4)
create table table2 (id int, type varchar(10))
insert into table2 (id, type) values (1,'A')
insert into table2 (id, type) values (2,'B')
insert into table2 (id, type) values (3,'C')
insert into table2 (id, type) values (4,'D')
表temp
是两个初始表的初始内部联接:
create table temp as
select a.*, b.*
from table1 a inner join table2 b on a.typeid = b.id
表cnt
具有每种类型的计数
create table cnt as
select c.type, count(1) as total
from temp c
group by type
最终表:
create table final as
select a.region, a.type
from table1 a inner join cnt c on a.type = c.type where c.total > 2
在给定的示例数据中,最终表应仅包含带有type = 2
的记录,因为type2
具有count > 2
请牢记当前的table1
和table2
包含数百万行。
非常感谢您。
答案 0 :(得分:0)
您可以使用CTE。因此,一种简化是:
table2
with cnt as (
select ?.typeid, count(*) as total
from table1 a
group by a.typeid
select a.region, a.typeid
from table1 a inner join
cnt c
on a.typeid = c.typeid
where c.total > 2;
对计数没有贡献,因此可以简化为:
select a.*
from (select a.*, count(*) over (partition by a.typeid) as cnt
from table1 a
) a
where cnt > 2;
如果您的窗口功能进一步简化了此操作
$(document).click(function (event) {
var clickover = $(event.target);
var $navbar = $(".navbar-top-collapse");
var _opened = $navbar.hasClass("in");
if (_opened === true && !clickover.hasClass("navbar-toggle collapsed")) {
$navbar.collapse('hide');
}
});
答案 1 :(得分:0)
如果您对表1的typeid进行分区,我相信这会更快。
create table #table1 (id int, region int, typeid int)
insert into #table1 (id, region, typeid ) values (1,2,1)
insert into #table1 (id, region, typeid ) values (2,3,1)
insert into #table1 (id, region, typeid ) values (3,4,2)
insert into #table1 (id, region, typeid ) values (4,1,2)
insert into #table1 (id, region, typeid ) values (5,1,2)
insert into #table1 (id, region, typeid ) values (6,2,4)
--exact your request:
select t.region, t.typeid from #table1 t where t.typeid in (select t.typeid from #table1 t group by t.typeid having count(t.typeid) > 2)
--...and if you need group:
select t.region, t.typeid, count(*)recordcount from #table1 t where t.typeid in (select t.typeid from #table1 t group by t.typeid having count(t.typeid) > 2) group by t.region, t.typeid
drop table #table1