从ACCESS TRANSFORM COUNT / PIVOT转换为SQL SERVER 2005

时间:2013-12-02 08:42:15

标签: sql-server vb.net pivot transform

需要一些帮助从访问 TRANSFORM COUNT / PIVOT 转换为 SQL SERVER ,以及来自访问的sql:

TRANSFORM Count(tmpTbl.TC) AS CountOfTC
SELECT tmpTbl.SID, tmpTbl.CSID, tmpTbl.M,WoOr.QCL
FROM tmpTbl INNER JOIN WoOr ON tmpTbl.WO = WoOr.WO
WHERE (((tmpTbl.IsSelected)=True))
GROUP BY tmpTbl.SID, tmpTbl.CSID, tmpTbl.M,WoOr.QCL
PIVOT tmpTbl.TN;

输出:

SID |   CSID | M |   QCL | EPA 1 | EPA 2 |
-----------------------------------------|
1   |   A    |GW |  IV   |  3    |       |
2   |   B    |GW |  IV   |       |  4    |
------------------------------------------

tmpTbl表中找到 3 EPA 1计数且 4 EPA 2计数。

先谢谢你了!

1 个答案:

答案 0 :(得分:2)

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;