0

I have 2 tables that I am joining.

Table 1 has 1-many relationship with table 2. That is, table 2 can return multiple rows for a single row of table 1. Because of this, the records of table 1 is duplicated for as many rows as are on table 2.. which is expected.

Now, I have a sum on one of the columns from table 1, but because of the multiple rows that get returned on the join, the sum is obviously multiplying.

Is there a way to get this number back to its original number? I tried dividing by the count of rows from table 2 but this didnt quite give me the expected result. Are there any analytical functions that could do this? I almost want something like "if this row has not yet been counted in the sum, add it to the sum"

4

2 回答 2

0

可能有一种更优化的方式来做到这一点,即使我对我现在为您提供的解决方案不满意,但暂时这对您有用。让其他大师开放:)

create table table1(id number,val number);
create table table2(id number,name varchar2(200));

insert into table1 values(1,1);
insert into table1 values(2,2);
insert into table1 values(3,3);

insert into table2 values(1,'gaurav');
insert into table2 values(1,'saurav');
insert into table2 values(1,'paurav');

insert into table2 values(2,'Rohan');
insert into table2 values(2,'Bhasker');
insert into table2 values(2,'Garima');


WITH tab as
(
SELECT id,sum(val) over() sum
FROM(
select DISTINCT t1.id,t1.val
from table1 t1,table2 t2 where t1.id=t2.id
))
SELECT tab.id,t2.id,t2.name,tab.sum
FROM table2 t2,tab
WHERE t2.id=tab.id

SQLFIDDLE:链接

于 2012-11-27T00:28:49.603 回答
0

如果没有示例结构/数据所需的结果等,很难确切知道,但这可能是您所追求的:

Select
  s.t1Sum,
  t1.*,
  t2.*
From (
    Select
      sum(col1) as t1Sum
    From
      Table1
    ) s
    Cross Join
  Table1 t1
    Inner Join
  Table2 t2
    On t1.Id = t2.FkId
于 2012-11-26T23:08:44.817 回答