SQL Pivot Table Subtotal Syntax error

2019-08-24 06:18发布

Hoping someone can help me. I was able to put together this SQL script but it coming back with minor errors here and there. I'be been trying to debug for over a week now. Please help. the first error message is "Incorrect syntax near ')'." If you fixe that it keeps on throwing more out so I'm thinking I'm not coding this correctly. I am unable to save changes that do work. it tell me the save request was aborted. Working with 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条回答
2楼-- · 2019-08-24 06:44

Hard to follow exactly what you're after, but I think you want Current Inventory to just be [1]+[2]+[3], and you didn't alias your subquery. The query at the bottom looks fine.

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