避免子查询和第二组?

时间:2014-11-23 04:04:28

标签: sql sql-server

我遇到了一些看似简单的事情,但我无法理解。

Table1 包含CountryID,CompanyID,PersonID,ItemID。 表2 包含几个引用特定CountryID和公司ID的AttributeID。

目标是查询每个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 个答案:

答案 0 :(得分: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;