1

这是我用来追踪员工休息日的表格。此示例仅适用于一个人。

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
4

1 回答 1

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

请参阅带有演示的 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 |
于 2012-11-28T11:27:48.530 回答