Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 20th, 2012  |  syntax: None  |  size: 1.77 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. SQL: Dynamic view with column names based on column values in source table
  2. ID  User    Description
  3.  
  4. 0   James   This is a support ticket
  5. 1   Fred    This is a ticket too
  6.        
  7. ID  TicketID    Label           Value
  8.  
  9. 0   0           Engineer        Scott
  10. 1   1           Engineer        Dale
  11. 2   0           Manu            Dell
  12. 3   1           Manu            HP
  13. 4   0           OS              Windows
  14. 5   1           OS              Linux
  15.        
  16. ID  User    Description                 Engineer    Manu    OS
  17.  
  18. 1   James   This is a support ticket    Scott       Dell    Windows
  19. 2   Fred    This is a ticket too        Dale        HP      Linux
  20.        
  21. select id, [user], [engineer], [manu], [OS]
  22. from
  23. (
  24.     select t.id
  25.         , t.[user]
  26.         , p.ticketid
  27.         , p.label
  28.         , p.value
  29.     from tickets t
  30.     inner join properties p
  31.         on t.id = p.ticketid
  32. ) x
  33. pivot
  34. (
  35.     min(value)
  36.     for label in ([engineer], [manu], [OS])
  37. ) p
  38.        
  39. DECLARE @cols AS NVARCHAR(MAX),
  40.     @query  AS NVARCHAR(MAX);
  41.  
  42. select @cols = STUFF((SELECT distinct ',' + QUOTENAME(p.label)
  43.                     from tickets t
  44.                     inner join properties p
  45.                         on t.id = p.ticketid
  46.             FOR XML PATH(''), TYPE
  47.             ).value('.', 'NVARCHAR(MAX)')
  48.         ,1,1,'')
  49.  
  50. set @query = 'SELECT id, [user], ' + @cols + ' from
  51.              (
  52.                  select t.id
  53.                         , t.[user]
  54.                         , p.ticketid
  55.                         , p.label
  56.                         , p.value
  57.                     from tickets t
  58.                     inner join properties p
  59.                         on t.id = p.ticketid
  60.             ) x
  61.             pivot
  62.             (
  63.                 min(value)
  64.                 for label in (' + @cols + ')
  65.             ) p '
  66.  
  67. execute(@query)