2014-11-23 67 views
0

我被看似容易的东西卡住了,但我无法弄清楚。避免子查询和第二组?

表1包含CountryID,CompanyID,PersonID,ItemID。 表2包含若干AttributeID,它们引用特定的CountryID和公司ID。

目标是查询每个CountryID中存在多少个AttributeID = 1的唯一CompanyID。

是否有更好的方法来实现这个比下面的解决方案?

http://sqlfiddle.com/#!3/c0d53/2/0

CREATE TABLE table1 
(
CountryID int, 
CompanyID int, 
PersonID int, 
ItemID int); 

INSERT INTO table1 (CountryID, CompanyID, PersonID, ItemID) 
VALUES (1,1,4,9),(1,1,6,3),(1,2,8,4),(1,2,4,1),(1,2,7,4),(2,1,1,2),(2,1,2,1),(2,2,5,1),(2,2,8,3),(2,2,10,2); 

CREATE TABLE table2 
(
CountryID int, 
CompanyID int, 
AttributeID int 
); 

INSERT INTO table2 (CountryID, CompanyID, AttributeID) 
VALUES (1,1,1),(1,1,2),(1,2,2),(1,2,5),(2,1,1),(2,2,1),(2,2,3),(2,2,5); 

的解决方案,我至今:

select t3.CountryID, count(*) as Count_of_Companies_with_AttributeID1 from 
(select t1.CountryID, t1.CompanyID from table1 t1 
inner join table2 t2 
on t1.CountryID=t2.CountryID and t1.CompanyID=t2.CompanyID 
where t2.AttributeID=1 
group by t1.CountryID, t1.CompanyID) as t3 
group by t3.CountryID 

感谢您的任何提示!

回答

1

我认为你可以做到这一点作为一个聚集查询与join

select t1.CountryId, count(distinct t2.CompanyId) 
from table1 t1 join 
    table2 t2 
    on t1.CountryID = t2.CountryID and t1.CompanyID = t2.CompanyID 
where t2.AttributeId = 1 
group by t1.CountryId;