首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从ACCESS转换计数/枢轴转换到SQL SERVER 2005

从ACCESS转换计数/枢轴转换到SQL SERVER 2005
EN

Stack Overflow用户
提问于 2013-12-02 08:42:14
回答 1查看 1.3K关注 0票数 0

需要一些帮助,从access TRANSFORM COUNT/PIVOT转换为SQL SERVER,下面是access中的sql:

代码语言:javascript
复制
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;

输出:

代码语言:javascript
复制
SID |   CSID | M |   QCL | EPA 1 | EPA 2 |
-----------------------------------------|
1   |   A    |GW |  IV   |  3    |       |
2   |   B    |GW |  IV   |       |  4    |
------------------------------------------

WHere发现3 EPA 1计数,4 EPA 2计数出现在tmpTbl表中。

预先谢谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-02 14:10:00

Server不使用TRANSFORM关键字和PIVOT将数据行转换为列。支点的基本语法将使用MSDN中的示例。

代码语言:javascript
复制
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查询的所有部分将在Server枢轴中的位置,语法就很容易编写。在Server中,当前的查询如下:

代码语言:javascript
复制
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来获得结果:

代码语言:javascript
复制
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;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20324003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档