计算另一个字段的每个组合的实例

时间:2013-06-11 19:53:03

标签: sql tsql

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

  1. OfficeID
  2. PropertyState
  3. PropertyAddress
  4. PropertyCity
  5. 我想找到超过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
    

1 个答案:

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

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

Here's SQL小提琴用于测试目的。