简体   繁体   中英

SQL join on two tables that are not related or have primary keys

I have the following query:-

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

Which results in something similar to this:-

service          level_3_structure   Total_Reduced
Service 1            Structure1          11.76
Service 2            Structure2         239.86
Service 3            Structure3         940.29

I have another table (table 2) which contains values service and level_3_structure and also contains a column called 'FTE'.

What I want to do, is join onto this table based on service and level_3_structure and return a sum of the FTE.

I have tried the below query, but it seems to duplicate table1 for each maching row, resulting in around 8.3 million results.

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

If your first query returns the rows you need, then you could join that (and not table1) to 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 

Still, it sounds like your table1 should have the column fte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM