2016-07-01 53 views
0

請幫助我! Newby with sql queries從查詢結果中刪除重複的列

Select * 
from(
    select EmpID, 
      sum(IncomeTax) as TaxAmount, 
      sum(bsalary) as SalaryAmount 
    from PayrollHistory Pay 
    group by EmpID 
) cumSalary 
Right JOIN (
    Select PayrollHistory.EmpID, 
      (select firstName +' '+coalesce(middleInitial,' ')+' '+ lastName 
      from Employee 
      where Employee.EmpID=PayrollHistory.EmpID)as name, 
      PayrollHistory.IncomeTax, 
      (PayrollHistory.bsalary+sum(ISNULL(Allw.amount,0)))totalTaxableSUM 
    from PayrollHistory 
    left join (
      select * 
      from AllowanceHistory 
      where AllowanceHistory.taxStatus=1 
      ) as Allw 
     on Allw.EmpID=PayrollHistory.EmpID and Allw.payMonth=PayrollHistory.payMonth 
    where PayrollHistory.payMonth=3 
    group by PayrollHistory.EmpID, PayrollHistory.IncomeTax, PayrollHistory.bsalary 
) as tbl 
    on tbl.EmpID =cumSalary.EmpID 

以上查詢結果給出了2個相同的EmpID行。如何刪除其中的一個,仍然可以得到相同的結果,而不是使用*

+2

此代碼很難閱讀。你可以應用一些格式? –

+0

請指定您的問題。你有重複的行或重複的列嗎? – Jonny

+0

請給我們一個輸出。 – CiccioRocca

回答

1

使用列名的選擇,參考以下

Select cumSalary.*,PayrollHistory.name , **....etc** from(
select EmpID, sum(IncomeTax) as TaxAmount,sum(bsalary) as SalaryAmount from  
PayrollHistory Pay group by EmpID 
) cumSalary 
Right JOIN (
Select PayrollHistory.EmpID,(select firstName +' '+coalesce(middleInitial,' 
')+' '+ lastName from Employee where 
Employee.EmpID=PayrollHistory.EmpID)as name, 
    PayrollHistory.IncomeTax,(  PayrollHistory.bsalary+sum(ISNULL(Allw.amount,0) 
))totalTaxableSUM 
from PayrollHistory 
left join (select * from AllowanceHistory where AllowanceHistory.taxStatus=1 
) as Allw on 
Allw.EmpID=PayrollHistory.EmpID and Allw.payMonth=PayrollHistory.payMonth 
where PayrollHistory.payMonth=3 
group by 
PayrollHistory.EmpID,PayrollHistory.IncomeTax,PayrollHistory.bsalary 
) as tbl on tbl.EmpID =cumSalary.EmpID 
2

相反的第一Select *指定您需要像所有行:

select cumSalary.EmpID, 
     cumSalary.TaxAmount, 
     cumSalary.SalaryAmount, 
     tbl.name, 
     tbl.IncomeTax, 
     tbl.totalTaxableSUM