SQL : query ยอดรวมจำนวนค่าซ่อมของแต่ละเดือน ได้ใน SQL คำสั่งเดียว ไม่ต้อง where ทีละเดือน

joy / 28 February, 2009 / Posted in อื่นๆ
อ่านเรื่องก่อนหน้านี้ «

อ่านเรื่องถัดไป »

วิธีเขียน 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



บทความนี้ถูกอ่านแล้ว : 1,633 ครั้ง

Related posts


อ่านเรื่องก่อนหน้านี้ «

อ่านเรื่องถัดไป »