如何结合内连接、子查询、求和和where条件

how to combine inner join, sub queries, sum and where condition

假设我有一个 table 如下所示:


员工号 |工资类型|工资|公司代码|


对于每个员工没有,我想创建一个table如下(我知道工资类型的数量)


唯一员工编号|总和(工资类型 1)|总和(工资类型 2)|公司代码


我正在使用以下代码,但是它不起作用...

select [Pers No ] ,["Co   Code"],[Company Code],
from [dbo].[Wages] as a 
    left join(
        select sum([[Total Wages])as [Total Wage Type 1 for Aug] 
        from [dbo].[Wages] 
        where [Wage Description] ='Wage Type 1' 
    ) as b on a.[Pers No ]=b.[Pers No ]
    left join(
        select sum([Total Wages]) as [Total Wage Type 2 for Aug] 
        from [dbo].[Wages] 
        where [Wage Description]='Wage Type 2'
    ) as c on b.[Pers No ] =c.[Pers No ]
group by[Pers No ], ["Co   Code"],[Company Code]
into [Total Wages Group by Pers No] 

基本上,我想获得每个员工每个工资类型组的工资总和。我的想法是最初按员工分组,然后在单个 select 语句中获得每种类型工资的总和,但这行不通。这就是为什么我现在使用 left join 的原因......但它也不起作用。

使用条件聚合可能有效:

select 
  [Pers No ],[Company Code],
  sum(case when [Wage Description] = 'OW for CPF' then [PwC_Totals] else 0 end) as [Total OW for Aug] ,
  sum(case when [Wage Description] = 'AW for CPF' then [PwC_Totals] else 0 end) as [Total AW for Aug] 
from [dbo].[OW and  AW - aug 14_cleaned] 
group by [Pers No ], [Company Code]

您的 table 中的列名称并不清晰,因此您可能需要对其进行调整。