SQL Server视图语法不正确

时间:2012-10-09 10:48:42

标签: sql sql-server-2008 view pivot-table

我有以下数据库:

My DB

我想创建一个连续提供此信息的视图:

document_id    Creator    Manager    Special    Archive  

(Creator,Manager,Special,Archive)是AuthorityName值

所以fisrt我创建了一个视图:

SELECT     dbo.DocumentAuthorities.DocumentId, dbo.DocumentAuthorities.AuthorityId,   dbo.Authorities.AuthorityName, dbo.Authorities.AuthorityLevel
FROM         dbo.DocumentAuthorities CROSS JOIN
                          dbo.Authorities
然后我尝试了这个:

 SELECT * FROM 
    (
    SELECT Documents.Id, AuthorityName.AuthorityId, AuthorityName.AuthorityName
    FROM AuthorityName CROSS JOIN Documents
     ) src 
     PIVOT
     ( 
        max(dbo.AuthorityName.AuthorityName) 
        FOR AuthorityName 
        IN ([Creator],[Director],[Special],[Archive])
      )

但是我收到了这个错误:

  

Msg 102,Level 15,State 1,Line 11')'附近的语法不正确。

1 个答案:

答案 0 :(得分:2)

试试这个:

您必须为数据透视表提供别名

SELECT * FROM 
(
SELECT Documents.Id, AuthorityName.AuthorityId, AuthorityName.AuthorityName
FROM AuthorityName CROSS JOIN Documents
 ) src 
 PIVOT
 ( 
    max(dbo.AuthorityName.AuthorityName) 
    FOR AuthorityName 
    IN ([Creator],[Director],[Special],[Archive])
  ) P -- < HERE