2012-12-26 113 views
1

我有3代表的Emp,Payroll_Emp和tbCompany 有Emp和tbCompanySQL把選擇的情況下,

沒有關係,我這樣做查詢,但即時得到了相同的CeilingEOS 我需要總結的所有員工每個員工ceilingEOS 我知道我必須把SUM(CeilingEOS)的選擇,但它不是工作壓力太大 有人可以幫我請

DECLARE @CeilingEOS decimal(18,2) 

SET @CeilingEOS=(select SUM (CeilingEOS) FROM Payroll_Emp inner join emp on Payroll_Emp.Employee_Id = Emp.[ID] where @Date>=Payroll_Emp.Payroll_From) 

select Emp.ID, tbCompany.ID, tbCompany.CompanyName, tbCompany.CEmpRepDesc, 
Emp.SSN, 

--case when Payroll_Emp.CeilingEOS IS NOT NULL then select SUM(CeilingEOS) as ceilingEOS 
from Payroll_Emp where Payroll_Emp.Employee_Id = Emp.[ID] group by Emp.ID end 


FROM tbCompany, Emp -- inner join Payroll_Emp on Payroll_Emp.Employee_Id = Emp.[ID] 
where @Date >= Emp.HireSince and Emp.ID=Emp.[ID] 

回答

0

你可以試試這個:

DECLARE 
    @CompanyID uniqueidentifier, 
    @CompanyName nvarchar(max), 
    @CEmpRepDesc nvarchar(max) 

select top 1 @CompanyID = tbCompany.ID, @CompanyName= tbCompany.CompanyName, @CEmpRepDesc = tbCompany.CEmpRepDesc from tbCompany 

select Emp.ID, Emp.SSN, ComputedInfos.CeilingEOS, @CompanyID, @CompanyName, @CEmpRepDesc 
from Emp 
left join (select Emp.ID as EmpID, SUM(CeilingEOS) as CeilingEOS from Emp join Payroll_Emp on Payroll_Emp.Employee_Id = Emp.[ID] where @Date >= Emp.HireSince group by Emp.ID) ComputedInfos 
    on ComputedInfos.EmpID = Emp.ID 
where @Date >= Emp.HireSince 
+0

我在表Emp和tbCompany之間沒有關係。 和羣由!!我認爲有更強大的功能可以用來代替編寫所有字段..有很多人使用你剛寫的內容,但我認爲這是錯誤的 – Nejthe

+0

你如何確定員工的公司? – fred

+0

只有一家公司,所有員工都屬於該公司 – Nejthe