2014-10-03 63 views
0

後,我想是這樣的:無效的列名PIVOT

42 | 41 | 31 | 32 | Name 
----------------------------  
O     42 
    X    41 
       P  32 
    Y    41 
    Z    41 

被轉動的列標題也都在名稱列中的值。各個列可以有不同的狀態。這是我有,但我不斷收到一個錯誤,說ValveGroupName列是無效的。

DECLARE @cols AS NVARCHAR(MAX), 
     @query AS NVARCHAR(MAX) 

select @cols = stuff((select ',' + quotename(ValveGroupName) 
         from dbo.adm_ValveGroup vgroup, 
          dbo.adm_Station station 
         where station.StationID = vgroup.StationID 
         and station.StationName in ('CBRN') 
         order by vgroup.ValveGroupName desc 
         for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') 

set @query = 'select ValveGroupName,' + @cols + ' from 
       (
       select vlog.status, 
         vgroup.ValveGroupName     
        from dbo.adm_Station station, 
         dbo.adm_ValveGroup vgroup, 
         dbo.valvegroup_log vlog 
       where station.StationID = vgroup.StationID 
        and vgroup.ValveGroupID = vlog.ValveGroupID 
        and station.StationName in (''CBRN'') 
        and vlog.logdate between ''2012-10-01'' and ''2012-10-30'' 
      ) x 
       pivot 
       (
       max(status) 
       for ValveGroupName in (' + @cols + ') 
      ) p ' 

execute (@query) 

這個查詢有什麼問題?

回答

1

由於您的ValveGroupName正在成爲PIVOT的新列名,所以通常不會將其包含在最終選擇列表中。由於您基本上「移除」了要成爲新列的ValveGroupName,因此SQL Server不再具有該列,因此會引發錯誤。

的代碼通常是:

set @query = 'select ' + @cols + ' 
      from 
      (
      select vlog.status, 
        vgroup.ValveGroupName     
       from dbo.adm_Station station 
       inner join dbo.adm_ValveGroup vgroup 
       on vgroup.ValveGroupID = vlog.ValveGroupID 
       inner join dbo.valvegroup_log vlog 
       on station.StationID = vgroup.StationID 
      where station.StationName in (''CBRN'') 
       and vlog.logdate between ''2012-10-01'' and ''2012-10-30'' 
     ) x 
      pivot 
      (
      max(status) 
      for ValveGroupName in (' + @cols + ') 
     ) p ' 

不過,既然你都聚集一個字符串,將返回一個單獨的行,每個ValveGroupName,如果要返回多行,那麼你就需要包括a row_number

set @query = 'select ' + @cols + ' 
      from 
      (
      select vlog.status, 
        vgroup.ValveGroupName, 
        seq = row_number() over(partition by vgroup.ValveGroupName    
              order by vlog.status) 
       from dbo.adm_Station station, 
       inner join dbo.adm_ValveGroup vgroup 
       on vgroup.ValveGroupID = vlog.ValveGroupID 
       inner join dbo.valvegroup_log vlog 
       on station.StationID = vgroup.StationID 
      where station.StationName in (''CBRN'') 
       and vlog.logdate between ''2012-10-01'' and ''2012-10-30'' 
     ) x 
      pivot 
      (
      max(status) 
      for ValveGroupName in (' + @cols + ') 
     ) p ' 

此更改將允許您返回每列中的多行。注意:我還將代碼更改爲使用INNER JOIN語法代替逗號連接,並使用WHERE子句中的條件。

+0

謝謝。如果我沒有進行任何左或右連接,爲什麼內連接而不是連接comman? – KrisW 2014-10-03 16:34:58

+0

@KrisW逗號語法是INNER JOIN。我將它改爲該語法,因爲這是SQL的當前標準。 – Taryn 2014-10-03 17:05:43