这是我追踪员工休假的表。此示例仅适用于一个人。
ID PID Year OffDays DayTypeNumber
------------------------------------------
1 1 2011 10 1
2 1 2011 5 2
3 1 2012 20 1
4 1 2012 3 2
我想写一个这样的查询,每年只能显示一个带有附加列的结果
Year OffDays(1) OffDays(2)
------------------------------------------
2011 10 5
2012 20 3
答案 0 :(得分:3)
您可以使用PIVOT
功能:
select year,
[1] [OffDays(1)],
[2] [OffDays(2)]
from
(
select year, offdays, daytypenumber
from yourtable
) src
pivot
(
sum(offdays)
for daytypenumber in([1], [2])
) piv
结果:
| YEAR | OFFDAYS(1) | OFFDAYS(2) |
----------------------------------
| 2011 | 10 | 5 |
| 2012 | 20 | 3 |
或者您可以使用带有CASE
语句的聚合函数:
select year,
sum(case when daytypenumber = 1 then offdays end) [OffDays(1)],
sum(case when daytypenumber = 2 then offdays end) [OffDays(2)]
from yourtable
group by year
如果您只有两种类型,那么您可以使用子查询:
select t1.year,
[OffDays(1)],
[OffDays(2)]
from
(
select sum(offdays) [OffDays(1)], year
from yourtable
where daytypenumber = 1
group by year
) t1
left join
(
select sum(offdays) [OffDays(2)], year
from yourtable
where daytypenumber = 2
group by year
) t2
on t1.year = t2.year
如果您有DayTypeNumber
的已知数量的值,上述答案将会很有效,但如果这些值未知,那么您可以使用动态SQL生成PIVOT
:
DECLARE @cols AS NVARCHAR(MAX),
@colNames AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DayTypeNumber)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colNames = STUFF((SELECT distinct ', ' + QUOTENAME(DayTypeNumber)
+' as [OffDays('+cast(DayTypeNumber as varchar(10))+')]'
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT year,' + @colNames + ' from
(
select year, offdays, daytypenumber
from yourtable
) x
pivot
(
sum(offdays)
for daytypenumber in (' + @cols + ')
) p '
execute(@query)
所有这些都会产生相同的结果:
| YEAR | OFFDAYS(1) | OFFDAYS(2) |
----------------------------------
| 2011 | 10 | 5 |
| 2012 | 20 | 3 |