mysql left join sum two tables with rollup

时光怂恿深爱的人放手 提交于 2019-12-23 02:53:35

问题


i stack at mysql syntax where i have a table revenue with values

title_id | revenue | cost
1 | 10 | 5
2   10  5
3   10  5
4   10  5
1   20  6
2   20  6
3   20  6
4   20  6

and then i have table fund with values

title_id | interest
1 | 10
2   10
3   10
4   10
1   20
2   20
3   20
4   20

I want to join this two table using left join and rollup the values like this :

SELECT R.title_id, 
   R.revenue, 
   R.cost, 
   F.interest 
FROM   (SELECT title_id, 
           Sum(revenue) revenue, 
           Sum(cost)    cost 
    FROM   revenue 
    GROUP  BY revenue.title_id with rollup) r 
   LEFT JOIN (SELECT title_id, 
                     Sum(interest) interest 
              FROM   fund 
              GROUP  BY title_id with rollup) f 
          ON r.title_id = F.title_id;

Output :

title_id | revenue | cost | interest
1   30  11  30
2   30  11  30
3   30  11  30
4   30  11  30
Total  120  44  null

But I want the output is :

title_id | revenue | cost | interest
1   30  11  30
2   30  11  30
3   30  11  30
4   30  11  30
Total  120  44  120

is this possible ? Thanks before


回答1:


Here's the details scenario:

With Data Given:

select a.title_id,  sum(revenue), sum(cost),sum(interest) from
(select a.title_id,  sum(revenue) as revenue, sum(cost) as cost from
(select  1 title_id, 10 revenue , 5 cost UNION all
select 2,   10,  5 UNION all
select 3,   10,  5 UNION all
select 4,   10,  5 UNION all
select 1,   20,  6 UNION all
select 2,   20,  6 UNION all
select 3,   20,  6 UNION all
select 4,   20,  6) as a
GROUP BY title_id) as a

left JOIN

(select title_id, sum(interest) as interest from
(select 1 as title_id, 10 as interest UNION all
select 2,   10 UNION all
select 3,  10 UNION all
select 4,   10 UNION all
select 1,  20 UNION all
select 2,  20 UNION all
select 3, 20 UNION all
select 4,  20) as b
GROUP BY title_id ) as b
on a.title_id = b.title_id 
GROUP BY a.title_id
with ROLLUP

result:

1   30  11  30
2   30  11  30
3   30  11  30
4   30  11  30
    120 44  120

final query structure:

select a.title_id,  sum(revenue), sum(cost),sum(interest) from
(select a.title_id,  sum(revenue) as revenue, sum(cost) as cost from
(select * from revenue) as a
GROUP BY title_id) as a

left JOIN

(select title_id, sum(interest) as interest from
(select * from fund) as b
GROUP BY title_id ) as b
on a.title_id = b.title_id 
GROUP BY a.title_id
with ROLLUP


来源:https://stackoverflow.com/questions/43600828/mysql-left-join-sum-two-tables-with-rollup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!