从两个表的SQL查询中获取总和

时间:2020-10-12 16:32:39

标签: sql sql-server sum powerbi inner-join

我有两个表,如下所示:

表1和表2。

表1:

select *
from mytable t
order by rank() over(partition by id order by time_point desc)
fetch first row with ties

表2:

Group   Id
___________
Jam     J1
Jam     J2
Jam     J3
Meyo    M1
Meyo    M2
Meyo    M3
Meyo    M4
Meyo    M5
Sauce   S1
Sauce   S2
Sauce   S3
Sauce   S4

我想要一个SQL查询,该查询将以整体方式向我显示结果。我想要的输出是:

Id  Shops  Companies
__________________
J1    20     5
J2    50     10
J3    30     10
M1    50     10
M2    50     10
M3    20     30
M4    80     25
M5    100    25
S1    50     10
S2    50     10
S3    100    30

我已经使用PowerBI做到了,我知道也可以使用SQL来完成,但是我无法实现。我已经准备好表以学习查询。如果我知道powerBI Measure与SQL查询有何不同还是相同,那也将是令人惊讶的。

预先感谢。

2 个答案:

答案 0 :(得分:2)

我看不到这些金额是累计。大概,您只需要聚合和常规和:

select t1.grp, sum(t2.shops) shops, sum(t2.companies) companies
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t1.grp

请注意,group是一种语言关键字,因此对于列名的选择不佳。我在查询中将其重命名为grp

答案 1 :(得分:0)

select Group ,  sum(Shops) as shops, sum(companies) as companies
from 
Table1
join Table2
on Table1.Id = Table2.Id
group by Table1.Group