[英]SQL join on two tables that are not related or have primary keys
我有以下查詢:-
select
dbo.table1.service,
dbo.table1.level_3_structure,
Sum(table1.Reduced) as Total_Reduced
from dbo.table1
where
dbo.table1.Period = 'Cumulative'
Group by
dbo.table1.service,
dbo.table1.level_3_structure
結果與此類似:-
service level_3_structure Total_Reduced
Service 1 Structure1 11.76
Service 2 Structure2 239.86
Service 3 Structure3 940.29
我有另一個表(表 2),其中包含值 service 和 level_3_structure,還包含一個名為“FTE”的列。
我想要做的是根據服務和 level_3_structure 加入這個表並返回 FTE 的總和。
我已經嘗試了下面的查詢,但它似乎為每個加工行復制了 table1,從而產生了大約 830 萬個結果。
select
dbo.table1.service,
dbo.table1.level_3_structure,
Sum(dbo.table1.Reduced) as Total_Reduced,
Sum(dbo.table2.fte) as 'Total FTE'
from dbo.table1
left join dbo.table2
on dbo.table1.service = dbo.table2.service and
dbo.table1.level_3_structure = dbo.table2.level_3_structure
where
dbo.table1.Period = 'Cumulative'
Group by
dbo.table1.service,
dbo.table1.level_3_structure
如果您的第一個查詢返回您需要的行,那么您可以將它(而不是 table1)加入到 table2:
select service, level_3_structure, Total_Reduced, sum(fte) as Total_FTE
from (
select
dbo.table1.service,
dbo.table1.level_3_structure,
Sum(table1.Reduced) as Total_Reduced
from dbo.table1
where
dbo.table1.Period = 'Cumulative'
Group by
dbo.table1.service,
dbo.table1.level_3_structure
) t1
inner join table2 on t1.service = table2.service
AND t1.level_3_structure = table2.level_3_structure
Group by
dbo.table1.service,
dbo.table1.level_3_structure
不過,聽起來您的 table1 應該有列 fte。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.