Convert from ACCESS TRANSFORM COUNT/PIVOT to SQL S

2019-06-08 19:51发布

Need some help converting from access TRANSFORM COUNT/PIVOT to SQL SERVER and here's the sql from access :

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;

OUTPUT:

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

WHere there are 3 EPA 1 count found and 4 EPA 2 count found IN tmpTbl Table.

Thank YOU in ADVANCE!

1条回答
The star\"
2楼-- · 2019-06-08 20:33

SQL Server doesn't use the TRANSFORM keyword along with PIVOT to convert the rows of data into columns. The basic syntax for a PIVOT will be using the sample from 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>

Once you understand where all of the pieces from your existing Access query will go in the SQL Server pivot, the syntax is easy to write. Your current query will be the following in 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;

If you have unknown values, then you will want to use dynamic SQL to get the result:

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;
查看更多
登录 后发表回答