总结麻烦和有条款

时间:2015-08-17 17:37:25

标签: tsql

我有一个查询填充“注销”小时的报告,其总数是RegHrs,OvtHrs和SpecialOvtHrs的总和,但只有那些具有正值的值(每个字段可能有正负值 - 正值被“注销”)。

我正在使用的查询(不起作用)是:

select
    LD.Employee,
    max(EM.LastName + ', ' + Em.FirstName) as EMName,
    LD.WBS1, LD.WBS2,
    sum(LD.RegHrs + LD.OvtHrs + LD.SpecialOvtHrs) as [Hours],
    CL.Name as ClientName,  pctf.CustProgram,
    max(PR.Name) as ProjName,
    LD.PKey, ISNULL(BillingDirectives.Comment, 'None') 
from AnvilProd..LD 
left join AnvilProd..PR on LD.WBS1 = PR.WBS1 and PR.WBS2 = ' ' and PR.WBS3 = ' '
left join AnvilProd..EM on LD.Employee = EM.Employee
left join AnvilProd..CL on PR.ClientID = CL.ClientID
left join AnvilProd..ProjectCustomTabFields pctf on PR.WBS1 = pctf.WBS1 and pctf.WBS2 = ' ' and pctf.WBS3 = ' '
left join InterfaceDev..BillingDirectives on BillingDirectives.PKey = LD.PKey   
where LD.BillStatus = 'X'
and LD.WrittenOffPeriod = @custPeriod
and LD.WBS1 not in (select distinct WBS1 from AnvilProd..BT where FeeBasis = 'L')
and LD.WBS1 not in (select distinct WBS1 from InterfaceDev..CircledHoursReportEliminatedJobs where ActiveStatus = 'Active')
group by pctf.CustProgram, CL.Name, LD.WBS1, LD.WBS2, LD.Employee, BillingDirectives.Comment, LD.PKey
-- having ((sum(LD.RegHrs) > 0) or (sum(LD.OvtHrs) > 0) or (sum(LD.SpecialOvtHrs) > 0))
order by pctf.CustProgram, CL.Name, LD.WBS1, WBS2, EMName

我需要为每个员工,WBS1,WBS2组合找到工作时间。

我用having条款尝试了十几种不同的东西,无法让它给我一个准确的结果。

1 个答案:

答案 0 :(得分:1)

@Override public void onClick(View v) { mSeries.clear(); mRenderer = new DefaultRenderer(); chartData.clear(); collectChartData(); fillPieChart(); }

中使用case
sum()

作为一种数学好奇心,你也可以用这种方式编码:

select blah, blah, 
  sum(
    case when LD.RegHrs > 0 then LD.RegHrs else 0 end +
    case when LD.OvtHrs > 0 then LD.OvtHrs else 0 end +
    case when LD.SpecialOvtHrs > 0 then LD.SpecialOvtHrs else 0 end
  ) as [Hours], blah, blah
from blah join blah ...
group by blah, blah
-- no having clause

尽管可读性稍差,但它使用的代码更少,可能会给同事留下更多的印象:)