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)
這個查詢有什麼問題?
謝謝。如果我沒有進行任何左或右連接,爲什麼內連接而不是連接comman? – KrisW 2014-10-03 16:34:58
@KrisW逗號語法是INNER JOIN。我將它改爲該語法,因爲這是SQL的當前標準。 – Taryn 2014-10-03 17:05:43