假设我有一个如下表:
员工否|工资类型|工资|公司代码|
对于每个员工不,我想创建一个如下表格(我知道工资类型的数量)
独特员工否|总和(工资类型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]
基本上,我想得到每个员工每个工资类型组的工资总额。我的想法是最初按员工分组,然后在单个选择语句中获得每种工资的总和,但这不起作用。这就是为什么我现在使用左连接...但它不能正常工作。
答案 0 :(得分:1)
使用条件聚合可能有效:
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]
表格中的列名称并非全部清除,因此您可能需要对其进行调整。