SQL数据透视表小计语法错误

时间:2014-03-17 20:05:54

标签: sql sql-server-2008-r2 syntax-error pivot subtotal

希望有人可以帮助我。我能够把这个SQL脚本放在一起,但它会在这里和那里发生一些小错误。我现在一直试图调试超过一周。请帮忙。第一条错误消息是"''附近的语法不正确。'。"如果你坚持认为它继续投入更多,所以我想我没有正确编码。我无法保存有效的更改。它告诉我保存请求已中止。使用SQL Server 2008 r2

SELECT     
PublicationID AS PubID, (PubNum + '-  ' + PubTitle) AS [Pub Descr], 
CONVERT(Varchar(10), [Datestamp], 101) AS [Date Printed], 
QtyPrinted AS [Qty Printed], 
[2] AS [Tyler Inventory], 
[1] AS [Central Inventory], 
[3] AS [Mailing House Inventory],

(
SELECT     SUM(S)
FROM  
(
SELECT [1] UNION ALL
SELECT [2] UNION ALL
SELECT [3]
) AS T (S)) AS [Current Inventory], 
RecycledQty AS [Recycled], 
MailingVendorName AS [Mailing Vendor], 
PrintVendorName AS [Print Vendor]

FROM
(
SELECT 
PublicationID, LocationID, Balance, PubNum, 
PubTitle, ItemPerCase, Datestamp, Deleted,     
RecycledQty, MailingVendorName, PrintVendorName, 
QtyPrinted

FROM          
(
dbo.view_PubInventory_Main_Summary_RAW) x PIVOT (sum(balance) FOR 
LocationID IN ([1],   [2], [3])) p)
    SELECT     *
     FROM  
     (SELECT   PUBID, [Pub Descr], [Date Printed], [Qty Printed], 
      [Tyler Inventory], [Central Inventory], 
      [Mailing House Inventory], [Current Inventory], [Recycled],
      [Mailing Vendor]
      FROM GG
      ) AS T

1 个答案:

答案 0 :(得分:0)

很难完全遵循您所追求的内容,但我认为您希望Current Inventory成为[1]+[2]+[3],并且您没有对子查询进行别名。底部的查询看起来很好。

 SELECT PublicationID AS PubID
      , PubNum + '-  ' + PubTitle AS [Pub Descr]
      , CONVERT(VARCHAR(10), [Datestamp], 101) AS [Date Printed]
      , QtyPrinted AS [Qty Printed]
      , [2] AS [Tyler Inventory]
      , [1] AS [Central Inventory]
      , [3] AS [Mailing House Inventory]
      , [1]+[2]+[3] AS [Current Inventory]
      , RecycledQty AS [Recycled]
      , MailingVendorName AS [Mailing Vendor]
      , PrintVendorName AS [Print Vendor]
 FROM   ( SELECT    PublicationID
                  , LocationID
                  , Balance
                  , PubNum
                  , PubTitle
                  , ItemPerCase
                  , Datestamp
                  , Deleted
                  , RecycledQty
                  , MailingVendorName
                  , PrintVendorName
                  , QtyPrinted
           FROM     dbo.view_PubInventory_Main_Summary_RAW
           PIVOT ( SUM(balance) FOR LocationID IN ( [1], [2], [3] ) ) p
        )AS Sub