วิธีเขียน sql query หายอดรวมจำนวนตัวเลขของแต่ละเดือน ได้ใน SQL คำสั่งเดียว ไม่ต้อง where ทีละเดือน
ตัวอย่างนี้ เป็นการหายอดรวมค่าซ่อมรถ ของรถทุกคัน แยกเป็นแต่ละเดือน
select license_no,
sum(case when month(bill_date)=1 then bill_amt else 0 end) as [Jan],
sum(case when month(bill_date)=2 then bill_amt else 0 end) as [Feb],
sum(case when month(bill_date)=3 then bill_amt else 0 end) as [Mar],
sum(case when month(bill_date)=4 then bill_amt else 0 end) as [Apr],
sum(case when month(bill_date)=5 then bill_amt else 0 end) as [May],
sum(case when month(bill_date)=6 then bill_amt else 0 end) as [Jun],
sum(case when month(bill_date)=7 then bill_amt else 0 end) as [Jul],
sum(case when month(bill_date)=8 then bill_amt else 0 end) as [Aug],
sum(case when month(bill_date)=9 then bill_amt else 0 end) as [Sep],
sum(case when month(bill_date)=10 then bill_amt else 0 end) as [Oct],
sum(case when month(bill_date)=11 then bill_amt else 0 end) as [Nov],
sum(case when month(bill_date)=12 then bill_amt else 0 end) as [Dec],
sum(bill_amt) as Total
from Bill_Head
where year(bill_date)=2008
group by license_no
order by license_no
Result
license_no | Jan | Feb | Mar | … | Dec| Total
74-1234 | 0 | 1000 | 2000 | … | 1000 | 4000
74-1235 | 50 | 1000 | 2000 | … | 2000 | 5050
คุณจอยเขียนโปรแกรมด้วยเหรอ เก่งนะน่ะ
พอเขียนได้ แต่ไม่เก่งหรอกนะ เหอๆ
โอ! บามา..
มันยอดมาก..