iT邦幫忙

0

請教各位高手以下sql語法需加入sum兩欄位相加分別於每個月

  • 分享至 

  • xImage

請教各位高手以下sql語法需加入sum兩欄位(PARTSTOTAL+MAINTAINEXPENSE)相加分別於每個月該如何下?

--新工作表八(維修費+零件費)0621
select t0.MECHANIC_NAME 維修人員, t0.PARTSTOTAL 實際更換零件, t0.MAINTAINEXPENSE 維修工資, sum(t0.m1) as '1月',sum(t0.m2) as '2月',sum(t0.m3) as '3月',sum(t0.m4) as '4月',sum(t0.m5) as '5月'
from 
	(
	SELECT MECHANIC_NAME,PARTSTOTAL,MAINTAINEXPENSE
		  ,year([RECEIVEDATE]) as year 
		  , case when month([RECEIVEDATE])=1 then SUM (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m1--(RECEIVEDATE 收件日期)
		  , case when month([RECEIVEDATE])=2 then SUM (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m2
		  , case when month([RECEIVEDATE])=3 then SUM (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m3
		  , case when month([RECEIVEDATE])=4 then SUM (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m4
		  , case when month([RECEIVEDATE])=5 then SUM (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m5
	  FROM wo 
	) t0
where t0.year=2022
group by t0.MECHANIC_NAME,t0.MAINTAINEXPENSE

https://ithelp.ithome.com.tw/upload/images/20220622/20148637XiqZxcvbDm.png

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
allenlwh
iT邦高手 1 級 ‧ 2022-06-23 09:21:55
最佳解答
select t0.MECHANIC_NAME 維修人員
--這裡的m1已經是實際更換零件+實際更換零件的加總了
, sum(t0.m1) as '1月',sum(t0.m2) as '2月',sum(t0.m3) as '3月',sum(t0.m4) as '4月',sum(t0.m5) as '5月'
from 
	(
	SELECT MECHANIC_NAME
		  ,year([RECEIVEDATE]) as year 		  
		  , case when month([RECEIVEDATE])=1 then (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m1--按月份計算 實際更換零件+實際更換零件
		  , case when month([RECEIVEDATE])=2 then (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m2
		  , case when month([RECEIVEDATE])=3 then (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m3
		  , case when month([RECEIVEDATE])=4 then (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m4
		  , case when month([RECEIVEDATE])=5 then (MAINTAINEXPENSE + PARTSTOTAL) else 0 end as m5
	  FROM wo 
	) t0
where t0.year=2022
group by t0.MECHANIC_NAME
yu0901 iT邦新手 4 級 ‧ 2022-06-23 09:36:12 檢舉

真的佩服!感謝allenlwh
我會好好努力
若你不介意再私聊我請uber eat送咖啡給您
輕鬆一下

我要發表回答

立即登入回答