如何治疗acct ='劳动'和acct ='劳工'在对列acct进行分组时也是如此

时间:2014-05-22 14:24:03

标签: sql sql-server

下面是我的查询:

select fiscalno, acct, data1, employee, project, pjt_entity,
 SUM(units) as units, SUM(amount) as amount, tr_id03, tr_id05, vendor_num
from dbo.PJTran
group by fiscalno, acct, data1, employee, project, pjt_entity, tr_id03, tr_id05, vendor_num
order by fiscalno, acct, employee

唯一的问题是,当在数据库中输入acct时,如果员工输入加班时间,则以laborlabor OT(加班)进入。因此,在将列组合在一起时,查询会将它们视为单独的。但是,我希望能够将劳工OT和劳动力一起归为同一领域。

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

你可以使用CASE函数作为Darka建议。这是查询的修改版本。它在acct值上使用CASE函数。 CTE用于避免在SELECT和GROUP BY语句中重复CASE语句。

WITH UPDATED_ACCT AS
(
  SELECT
  fiscalno, (CASE WHEN acct = 'labor ot' THEN 'labor' ELSE acct END) acct, data1, employee, project, pjt_entity, units, amount, tr_id03, tr_id05, vendor_num
  FROM DBO.PJTRAN
)
SELECT 
  FISCALNO, ACCT, DATA1, EMPLOYEE, PROJECT, PJT_ENTITY, SUM(UNITS) AS UNITS, SUM(AMOUNT) AS AMOUNT, TR_ID03, TR_ID05, VENDOR_NUM
FROM UPDATED_ACCT
GROUP BY fiscalno, acct, data1, employee, project, pjt_entity, tr_id03, tr_id05, vendor_num
ORDER BY FISCALNO, ACCT, EMPLOYEE  ;

<强>参考

Using CASE statement within GROUP BY on MSDN

答案 1 :(得分:0)

select
fiscalno, CASE WHEN acct='labor ot' then 'labor'else acct end as 'acct', data1, employee, project, pjt_entity, SUM(units) as units, SUM(amount) as amount, tr_id03, tr_id05, vendor_num
from dbo.PJTran 
group by fiscalno, CASE WHEN acct='labor ot' then 'labor'else acct end, data1, employee, project, pjt_entity, tr_id03, tr_id05, vendor_num
order by fiscalno, acct, employee