您可以为此使用该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
请参阅带有演示的 SQL Fiddle
结果:
| 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
请参阅带有演示的 SQL Fiddle
如果您只有两种要比较的类型,那么您可以使用子查询:
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
请参阅带有演示的 SQL Fiddle
如果您有已知数量的值,上述答案将非常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)
请参阅带有演示的 SQL Fiddle
所有这些都会产生相同的结果:
| YEAR | OFFDAYS(1) | OFFDAYS(2) |
----------------------------------
| 2011 | 10 | 5 |
| 2012 | 20 | 3 |