SQL Server 不使用 TRANSFORM 关键字和 PIVOT 将数据行转换为列。 PIVOT 的基本语法将使用来自MSDN 的示例:
SELECT <non-pivoted column>, -- your final columns displayed will be in this select
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(
<SELECT query that produces the data> -- the FROM will include your existing select from/join
) AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>) -- your count Count(tmpTbl.TC)
FOR
[<column that contains the values that will become column headers>] -- the FOR includes the tmpTbl.TN
IN ( [first pivoted column], [second pivoted column], -- the IN will be your EPA1 and EPA2 values
... [last pivoted column])
) AS <alias for the pivot table>
一旦您了解现有 Access 查询中的所有部分在 SQL Server 数据透视表中的位置,就可以轻松编写语法。您当前的查询将在 SQL Server 中如下所示:
select sid, csid, m, qcl, [EPA 1], [EPA 2]
from
(
select t.sid, t.csid, t.m, w.qcl, t.tc, t.tn
from tmpTbl t
inner join WoOr w
on t.wo = w.wo
where t.isselected = 1
) d
pivot
(
count(tc)
for tn in ([EPA 1], [EPA 2])
) piv;
如果你有未知的值,那么你会想要使用动态 SQL 来获取结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(tn)
from tmpTbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT sid, csid, m, qcl, ' + @cols + '
from
(
select t.sid, t.csid, t.m, w.qcl, t.tc, t.tn
from tmpTbl t
inner join WoOr w
on t.wo = w.wo
where t.isselected = 1
) x
pivot
(
count(tc)
for tn in (' + @cols + ')
) p '
execute sp_executesql @query;