Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅对Sql Server中的不同行求和_Sql - Fatal编程技术网

仅对Sql Server中的不同行求和

仅对Sql Server中的不同行求和,sql,Sql,我有四个表,其中第一个表与其余三个表(分别命名为Second、Third、Fourth)有一对多的关系。我只想对select查询返回的不同行求和。这是我的查询,到目前为止我一直在尝试 select count(distinct First.Order_id) as [No.Of Orders],sum( First.Amount) as [Amount] from First inner join Second on First.Order_id=Second.Order_id inner

我有四个表,其中第一个表与其余三个表(分别命名为Second、Third、Fourth)有一对多的关系。我只想对select查询返回的不同行求和。这是我的查询,到目前为止我一直在尝试

select count(distinct First.Order_id) as [No.Of Orders],sum( First.Amount) as [Amount] from First 
inner join Second  on First.Order_id=Second.Order_id
inner  join Third  on Third.Order_id=Second.Order_id
inner  join  Fourth  on Fourth.Order_id=Third.Order_id
此查询的结果是:

No.Of Orders                       Amount
7                                  69

但是这个数量应该是49,因为第一列的数量之和是49,但是由于内部联接和一对多关系,它会计算重复行的数量之和。如何避免这种情况。请指导我。我认为问题是给定id的联接中的笛卡尔积。您可以使用行数解决这个问题:

顺便说一句,您也可以在where子句中使用条件来表示这一点,因为您似乎只将联接用于过滤:

select count(First.Order_id) as [No.Of Orders], sum(First.Amount) as [Amount]
from First
where exists (select 1 from second where First.Order_id=Second.Order_id) and
      exists (select 1 from third where First.Order_id=third.Order_id) and
      exists (select 1 from fourth where First.Order_id=fourth.Order_id);

谢谢,您的第一个查询给了我错误。无法绑定多部分标识符first.Order\u id。
select count(First.Order_id) as [No.Of Orders], sum(First.Amount) as [Amount]
from First
where exists (select 1 from second where First.Order_id=Second.Order_id) and
      exists (select 1 from third where First.Order_id=third.Order_id) and
      exists (select 1 from fourth where First.Order_id=fourth.Order_id);