我有一张这样的表:
leave_id applicant from_date to_date type status
1 a 2/7/2014 5/7/2014 Annual Approve
2 Basudev 2/7/2014 5/7/2014 Annual Approve
3 Basudev 2/7/2014 5/7/2014 Casual Approve
4 Basudev 2/7/2014 5/7/2014 Sick Approve
5 a 2/7/2014 5/7/2014 Casual Approve
6 a 2/7/2014 5/7/2014 Sick Approve
我想要一份这样的报告:
applicant annual casual sick
a 2 4 6
Basudev 1 4
我正在使用此查询
select a.applicant,
case when a.type='Annual'
Then (DATEDIFF(to_date,from_date))+1
Else ''
End as Annual_consume,
case when a.type='Casual'
Then (DATEDIFF(to_date,from_date))+1
Else ''
End as Casual_consume,
case when a.type='Sick'
Then (DATEDIFF(to_date,from_date))+1
Else ''
End as Sick_consume
from leaves a
order by applicant
但它显示的数据如下:
applicant annual casual sick
a 2
a 4
a 6
Basudev 2
Basudev 3
请帮助解决此问题。
答案 0 :(得分:0)
select a.applicant,
sum(case when a.type='Annual' Then (DATEDIFF(to_date,from_date))+1 end) as Annual_consume,
sum(case when a.type='Casual' Then (DATEDIFF(to_date,from_date))+1 end) as Casual_consume,
sum(case when a.type='Sick' Then (DATEDIFF(to_date,from_date))+1 end) as Sick_consume
from leaves a
group by a.applicant
order by a.applicant
答案 1 :(得分:0)
SELECT a.applicant,
SUM(
CASE
WHEN a.type='Annual'
THEN (DATEDIFF(to_date,from_date))+1
END) AS Annual_consume,
SUM(
CASE
WHEN a.type='Casual'
THEN (DATEDIFF(to_date,from_date))+1
END) AS Casual_consume,
SUM(
CASE
WHEN a.type='Sick'
THEN (DATEDIFF(to_date,from_date))+1
END) AS Sick_consume
FROM leaves a
ORDER BY applicant
GROUP BY applicant