SQL Pivot on dates column?

前端 未结 1 514
执念已碎
执念已碎 2021-01-05 15:32

I\'m fairly new to SQL but believe me I have searched for help before posting this.

I have a query which returns a list of people assigned to jobs, also the jobs hav

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 15:48

    If you are going to be running this query in SQL Server, then you can use the PIVOT function:

    select *
    from
    (
      select role, familyname, givenname, skill,
        level, id, date, 'Y' flag
      from yourtable
    ) src
    pivot
    (
      max(flag)
      for date in ([2013-03-27], [2013-03-26],
                   [2013-03-25], [2013-03-24])
    ) piv
    

    See SQL Fiddle with Demo

    Or you can use an aggregate function and a CASE statement:

    select role, familyname, givenname, skill,
      level, id,
      max(case when date = '2013-03-27' then flag end) '2013-03-27',
      max(case when date = '2013-03-26' then flag end) '2013-03-26',
      max(case when date = '2013-03-25' then flag end) '2013-03-25',
      max(case when date = '2013-03-24' then flag end) '2013-03-24'
    from
    (
      select role, familyname, givenname, skill,
        level, id, date, 'Y' flag
      from yourtable
    ) src
    group by role, familyname, givenname, skill,
      level, id
    

    See SQL Fiddle with Demo

    Both give the result:

    |              ROLE | FAMILYNAME | GIVENNAME | SKILL |           LEVEL |  ID | 2013-03-27 | 2013-03-26 | 2013-03-25 | 2013-03-24 |
    ----------------------------------------------------------------------------------------------------------------------------------
    | Vision Supervisor |   Unsworth |     Simon |    10 | Telegenic Staff | 664 |          Y |          Y |          Y |          Y |
    

    The above works great if you know the values to transpose, but you if you don't then you can use dynamic sql similar to this:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT ',' + QUOTENAME(convert(char(10), date, 120)) 
                        from yourtable
                        group by date
                        order by date desc
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT role, familyname, givenname, skill,
                        level, id,' + @cols + ' from 
                 (
                    select role, familyname, givenname, skill,
                        level, id, date, ''Y'' flag
                    from yourtable
                ) x
                pivot 
                (
                    max(flag)
                    for date in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    See SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题