Sql-Server-2014

添加額外的總列,對每一行的所有列值求和

  • April 21, 2018

我有以下查詢

SELECT 'Total_Invoices', SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM OINV T0 WHERE T0.[Series] <>'80'  AND
DateDiff(MM,T0.DocDate,'2017-02-02')=0
UNION ALL
SELECT 'Total_DownPayment', SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ODPI T0 WHERE
DateDiff(MM,T0.DocDate,'2017-02-02')=0
UNION ALL
SELECT 'Total_CreditNotes', (SUM(T0.[VatSum])-SUM(T0.[WTSum]))-SUM(T0.[DocTotal]) as "Amnt(Exl)", -SUM(T0.[VatSum]) as "VAT", -SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ORIN T0 WHERE T0.[Series]='5' AND 
DateDiff(MM,T0.DocDate,'2017-02-02')=0

輸出是: 在此處輸入圖像描述

我想創建一個額外的列,添加第四列,其中包含三行的行總數。我嘗試了以下方法無濟於事:

;WITH CTE AS 
(
SELECT * FROM
(
   SELECT  SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM OINV T0 WHERE T0.[Series] <>'80'  AND
   DateDiff(MM,T0.DocDate,'2017-02-02')=0 
)AS Qry1
   UNION ALL
   SELECT * FROM
(
   SELECT SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ODPI T0 WHERE
   DateDiff(MM,T0.DocDate,'2017-02-02')=0
)AS Qry2
   UNION ALL
   SELECT * FROM
(
   SELECT (SUM(T0.[VatSum])-SUM(T0.[WTSum]))-SUM(T0.[DocTotal]) as "Amnt(Exl)", -SUM(T0.[VatSum]) as "VAT", -SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ORIN T0 WHERE T0.[Series]='5' AND 
   DateDiff(MM,T0.DocDate,'2017-02-02')=0
)AS Qry3
)
SELECT *, Qry1 + Qry2 + Qry3 AS TotalSum
FROM CTE

我如何達到第 4 列的總數?

我不確定您是否需要您正在嘗試的 CTE。似乎您正在完成第一個查詢中所需的所有工作,並且可以將其用作 CTE。

這是一個你可以執行的模型:

我將您的第一列命名為“類別”,這樣您就可以在最後的SELECT陳述中使用一些東西。還包圍了要單獨添加的值,ISNULL([Value],0)這樣任何NULL值都不會造成麻煩。

希望這個對你有幫助。

WITH CTE_Data
AS
(
SELECT 'Total_Invoices' AS Category, SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM OINV T0 WHERE T0.[Series] <>'80'  AND
DateDiff(MM,T0.DocDate,'2017-02-02')=0
UNION ALL
SELECT 'Total_DownPayment', SUM(T0.[DocTotal]) - (SUM(T0.[VatSum])-SUM(T0.[WTSum])) as "Amnt(Exl)", SUM(T0.[VatSum]) as "VAT", SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ODPI T0 WHERE
DateDiff(MM,T0.DocDate,'2017-02-02')=0
UNION ALL
SELECT 'Total_CreditNotes', (SUM(T0.[VatSum])-SUM(T0.[WTSum]))-SUM(T0.[DocTotal]) as "Amnt(Exl)", -SUM(T0.[VatSum]) as "VAT", -SUM(T0.[DocTotal]) as "Amnt(Incl)" FROM ORIN T0 WHERE T0.[Series]='5' AND 
DateDiff(MM,T0.DocDate,'2017-02-02')=0
)

SELECT Category, 
      [Amnt(Exl)],
      [VAT],
      [Amnt(Incl)],
      ISNULL([Amnt(Exl)],0) + ISNULL([VAT],0) + ISNULL([Amnt(Incl)],0) AS SumRequested
FROM CTE_Data;

引用自:https://dba.stackexchange.com/questions/204592