2013-07-12 79 views
0

我在SAP B1中列出了一週中銷售額的SQL查詢。我也有一個查詢,使這些相同的銷售總和。我如何組合查詢,以便結果是銷售額的所有行,並且在這些行下面顯示的總和爲一行?SQL列表和總和

SQL查詢 - 列出

SELECT T0.[DocNum], T0.[DocDate], 
     T1.[CardName], T1.[CardFName], T0.[DocTotalSy] AS Total 
    FROM ORDR T0 
    INNER JOIN OCRD T1 
    ON T0.CardCode = T1.CardCode 
    WHERE T0.[DocDate] > (SELECT CONVERT(varchar(10), DATEADD(day, -6, GETDATE()), 101)) 

SQL查詢 - 琛

SELECT SUM (T0.[DocTotalSy]) AS Total 
    FROM ORDR T0 
    INNER JOIN OCRD T1 
    ON T0.CardCode = T1.CardCode 
    WHERE T0.[DocDate] > (SELECT CONVERT(varchar(10), DATEADD(day, -6, GETDATE()), 101)) 

回答

1

我想你想的group by with rollup聲明(描述here):

SELECT T0.[DocNum], T0.[DocDate], T1.[CardName], T1.[CardFName], sum(T0.[DocTotalSy]) AS Total 
FROM ORDR T0 INNER JOIN 
    OCRD T1 
    ON T0.CardCode = T1.CardCode 
WHERE T0.[DocDate] > (SELECT CONVERT(varchar(10), DATEADD(day, -6, GETDATE()), 101)) 
group by T0.[DocNum], T0.[DocDate], T1.[CardName], T1.[CardFName] with rollup 

然而,這可能不是正是你想要的。我可以看到,rollupgrouping sets都適用於您的查詢,但很難準確確定哪些內容會生成您想要的內容。樣本結果總是有助於有效溝通。

0

您可以在現有的第一查詢添加的總和,然後通過使用組:

SELECT T0.[DocNum], T0.[DocDate], T1.[CardName], T1.[CardFName], T0.[DocTotalSy] AS Total, sum(T0.[DocTotalSy]) AS SumTotal 
FROM ORDR T0 INNER JOIN 
    OCRD T1 
    ON T0.CardCode = T1.CardCode 
WHERE T0.[DocDate] > (SELECT CONVERT(varchar(10), DATEADD(day, -6, GETDATE()), 101)) 
group by T0.[DocNum], T0.[DocDate], T1.[CardName], T1.[CardFName]