sql - 使用 SUM 函数在 SQL 中连接表

标签 sql inner-join sql-server-2012

我正在使用 SQL Server 2012 并有以下表格:Ownership , Property , Person
Person保存有关人的信息,例如名字、姓氏,此表有 PersonId作为主键。

Property保存有关属性的信息,例如属性区域、属性描述.. 并且此表有 PropertyId作为主键

因为每个人可以拥有多个属性(property),而一个属性(property)的每个所有权也可以不止一个人,那么我们就有了Person之间的多对多关系。和 Property
所以我创建了表 Ownership打破这种关系,所以这张表有PersonIdPropertyId作为外键,以及以下列:PropertyId作为“主键”,StartDate , EndDateOwnershipPercent .
Start DateEnd Date指属性(property)归某人所有的时期,以及OwnershipPercent指该人对属性(property)的份额。

现在我想写一个查询来返回一个人同时拥有超过 100% 的任何属性(property)

例如:

属性(property)与 Id=1从 1-1-2010 到 1-1-2012 属于 #1 的人,他在该属性(property)中的份额为 90%,并且该属性(property)也属于另一个在 1-1-2010 到 1-1- 期间拥有 #2 的人2012 年,他在该属性(property)中的份额为 80% .. 正如我们看到的,如果我们同时求和 90+80=170%,这是错误的(因为同时小于 100%)

我写了以下查询:

SELECT A.PropertyId
FROM Ownership A INNER JOIN Ownership B
ON a.PersonId <> b.PersonId
AND A.PropertyId = B.PropertyId
AND A.StartDate <= B.EndDate
AND A.EndDate >= B.StartDate
group by A.PropertyId
Having (sum(A.OwnershipPercent)) <=100; 

但是如果我们有一个属于 5 个人的属性(property),那么 (5×4)=20 和这是错误的

如何解决这个问题?

最佳答案

我认为在所有权表上加入的方法不太正确。我明白你在做什么,但加入正在创建成对的所有者。相反,您要考虑所有者集。

我的方法是为每个属性创建一个包含所有重要日期的表格。这将是 OwnerShip 表中的 StartDate 和 EndDate。然后,让我们看看这些日期的所有权百分比:

select os.PropertyId, thedate, SUM(os.OwnershipPercent)
from ((select PropertyId, StartDate as thedate
       from ownership
      )union
      (select PropertyId, EndDate
       from ownership
      )
     ) driver join
     OwnerShip os
     on driver.PropertyId = os.PropertyId and
        driver.thedate between os.StartDate and os.EndDate
group by os.PropertyId, thedate
having SUM(os.OwnershipPercent) <= 100  -- Do you really want > 100 here?

一个主要区别是此查询聚合了 PropertyId 和日期。这是有道理的,因为所有权的数量会随着时间的推移而变化。

关于sql - 使用 SUM 函数在 SQL 中连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14122005/

相关文章:

sql - 在 SQL Server 中将 s、t 与 ş、ţ 进行比较

MySQL Connector/J v5.x 升级 : query now returning byte[] instead of String

sql - Postgres JSON 数组带有连接?

带内连接的 Mysql 查询

SQL查询无条件选择两个表的记录

sql - 从 SQL Server 中的字符串末尾删除连字符

mysql - 如何解决基于运行ac_principal的运行principal问题?

sql - Azure 使用 SSIS 将数据从 1 db 复制到另一个 db

mysql - SQL 内连接 - 性能改进

mysql - 我可以在 MySQL 查询中使用 preg_replace 或 regex 吗?