SQL内部连接总和

时间:2018-07-11 08:20:36

标签: sql oracle sum inner-join

我在下面有2张桌子。我想加入它们并查看c2列的总和,但sum(table2.c2)结果显示为18而不是9。我该如何纠正?

表1:

c1 c2  
a  6
a  0

表2

c1  c2
a   9
select table1.c1 ,sum(table1.c2), table2.c1, sum(table2.c2)
from table1
inner join table2
on table1.c1=table2.c1
GROUP BY table1.c1 ,table2.c1

结果如下:

table1.c1   sum(table1.c2)  table2.c1   sum(table2.c2)
a           6               a           18

我希望这样:

table1.c1   sum(table1.c2)  table2.c1   sum(table2.c2)
a           6               a           9

3 个答案:

答案 0 :(得分:1)

您想在SUM之前做JOIN

select t1.c1, t1.sumc2, t2.c2, t2.sumc2
from (select c1, sum(c2) sumc2 from table1 group by c1) t1
join (select c1, sum(c2) sumc2 from table2 group by c1) t2 on t1.c1 = t2.c1

答案 1 :(得分:1)

这是因为您在table1.c1 = table2.c1上进行内部联接,而table1有两行,导致table2中的单行像这样重复。

c1  t1.c2   t2.c2 
a     6       9 
a     0       9

因此,总和将为6和18。您可以通过在表中添加行号或在连接表之前使用内部选择或视图求和来解决此问题。

答案 2 :(得分:0)

尝试一下

;WITH hourlist(starthour) AS (
  SELECT 0     -- Seed Row
  UNION ALL
  SELECT starthour + 1 -- Recursion
  FROM hourlist
  where starthour+1<=23
)
SELECT 
    day
    ,convert(nvarchar,starthour)+'-'+convert(nvarchar,case when starthour+1=24 then 0 else starthour+1 end) hourtitle
    ,count(distinct customer_id) 'customer count'
FROM 
    hourlist h -- list of all hourse
    cross join 
    (
        select distinct dateadd(day,datediff(day,0, joinTime),0) from #login_out_logs 
        union
        select distinct dateadd(day,datediff(day,0,leaveTime),0) from #login_out_logs
    )q10(day)  -- list of all days of jointime and leavetime
    inner join #login_out_logs l on -- log considered for specific day/hour if starts before hourend and ends before hourstart
        l.joinTime <dateadd(hour,starthour+1,q10.day)
        and
        l.leaveTime>=dateadd(hour,starthour  ,q10.day)
group by day,starthour
order by day,starthour