仅在Sql Server中汇总不同的行

时间:2014-05-01 16:30:17

标签: sql

我有四个表,其中First与三个表的其余部分有一对多关系,分别命名为(SecondThirdFourth)。我想要只选择查询返回的不同行。这是我的查询,我到目前为止尝试。

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

但是这个Amount应该 49 ,因为第一列Amount的总和是 49 ,但是由于内部联接和一个到很多关系,它计算了重复行的总和。如何避免这种情况。请指导我

1 个答案:

答案 0 :(得分:0)

我认为问题是联接中的笛卡尔积(对于给定的id)。您可以使用row_number()

解决此问题
select count(t1234.Order_id) as [No.Of Orders], sum(t1234.Amount) as [Amount]
from (select First.*,
             row_number() over (partition by First.Order_id order by First.Order_id) as seqnum
      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
     ) t1234
where seqnum = 1;

顺便说一句,您也可以使用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);