SQL子查询不会是SUM

时间:2017-06-23 09:03:11

标签: sql-server sap

这是我正在创建的查询。它有效,但给出结果 - 一个用于发票,一个用于信用。我只想要一个结果 - 总数。即发票减去信用票据。

SELECT 
sum ([linetotal])
FROM
(
SELECT
sum(t1.[LineTotal])  AS 'Linetotal'
FROM OINV T0  
INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry 
INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode 
WHERE t0.taxdate >= '20170101' and t0.taxdate <= '20170131'  and t0.[canceled] ='n' and  T0.[SlpCODE] = '4'

union all

SELECT
sum(-T1.[LineTotal] ) AS 'Linetotal'
FROM ORIN T0 
INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry 
INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode 
WHERE t0.taxdate >= '20170101' and t0.taxdate <= '20170131'  and t0.[canceled] ='n' and  T0.[SlpCODE] = '4'
)
as a
group by a.linetotal

2 个答案:

答案 0 :(得分:1)

您必须删除分组。

SELECT 
sum ([linetotal])
FROM
(
SELECT
sum(t1.[LineTotal])  AS 'Linetotal'
FROM OINV T0  
INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry 
INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode 
WHERE t0.taxdate >= '20170101' and t0.taxdate <= '20170131'  and t0.[canceled] ='n' and  T0.[SlpCODE] = '4'

union all

SELECT
sum(-T1.[LineTotal] ) AS 'Linetotal'
FROM ORIN T0 
INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry 
INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode 
WHERE t0.taxdate >= '20170101' and t0.taxdate <= '20170131'  and t0.[canceled] ='n' and  T0.[SlpCODE] = '4'
)
as a

答案 1 :(得分:0)

尝试删除最后一行:group by a.linetotal,因为它们将它们分开,因为它们不等于