1

我有一个包含以下字段的表:

  1. 办公室编号
  2. 属性状态
  3. 属性地址
  4. 地产城

我想查找超过 1 个 OfficeID 为特定地址(St、City、Addr 相等)打开文件的所有属性,以及为每个办公室组合打开了多少具有相同地址的文件。

例如给定下面的数据集:

OfficeID      PropertySt       PropertyCity       PropertyAddr
   1             NC               Raleigh            123 Main St
   1             NC               Raleigh            456 Acorn Ave
   1             NC               Raleigh            789 Blue Rd
   2             NC               Raleigh            123 Main St
   2             NC               Raleigh            321 South St
   3             NC               Raleigh            456 Acorn Ave
   3             NC               Raleigh            789 Blue Rd
   3             NC               Raleigh            987 West St
   4             NC               Raleigh            123 Main St
   4             NC               Raleigh            987 West St

我希望

   OfficeCombo   Count
      1/2           1
      1/3           2
      1/4           1
      2/3           0 (this row would not NEED to be returned but is ok to return with a 0)
      2/4           1
      3/4           1
4

1 回答 1

0

这应该可以解决问题:

select
  cast(A.OfficeId as varchar(10)) + '/' +
  cast(B.OfficeId as varchar(10)) as OfficeCombo,
  count(*) as [Count]
from Table1 A join Table1 B
   on A.PropertySt = B.PropertySt
  and A.PropertyCity = B.PropertyCity
  and A.PropertyAddr = B.PropertyAddr
  and B.OfficeId > A.OfficeId
group by A.OfficeId, B.OfficeId

这个想法是计算每对办公室有多少个共同地址。

这是一个用于测试目的的 SQL Fiddle。

于 2013-06-11T20:08:50.617 回答