SQL查询的麻烦(差分和)

时间:2014-04-09 08:29:32

标签: sql sql-server

我有这个问题:

SELECT DISTINCT MA_CustSupp.CompanyName, MA_CustSupp.TaxIdNumber, SUM(MA_SaleDocSummary.GoodsAmount) AS somma, SUM(MA_SaleDocSummary.ShippingCharges) 
AS ship, MA_CustSupp.CustSupp, MA_CustSupp.FiscalCode, COUNT(MA_SaleDoc.DocumentType) AS conto, MA_CustSuppCustomerOptions.Category
FROM  MA_CustSuppCustomerOptions INNER JOIN
                         MA_CustSupp ON MA_CustSuppCustomerOptions.Customer = MA_CustSupp.CustSupp INNER JOIN
                         MA_SaleDoc INNER JOIN
                         MA_SaleDocSummary ON MA_SaleDoc.SaleDocId = MA_SaleDocSummary.SaleDocId ON MA_CustSupp.CustSupp = MA_SaleDoc.CustSupp
WHERE        (MA_SaleDoc.IncludedInTurnover = 1) AND (MA_SaleDoc.CustSuppType = 3211264) AND (MA_SaleDoc.DocumentDate >= CONVERT(DATETIME, 
                         '2014-04-01 00:00:00', 102)) AND (MA_SaleDoc.DocumentDate <= CONVERT(DATETIME, '2014-04-08 00:00:00', 102)) AND (MA_CustSupp.CustSupp <> '022428')
GROUP BY MA_CustSupp.CompanyName, MA_CustSupp.CustSupp, MA_CustSupp.TaxIdNumber, MA_CustSupp.FiscalCode, MA_SaleDoc.DocumentType, 
                         MA_CustSuppCustomerOptions.Category
HAVING        (MA_CustSuppCustomerOptions.Category = '06') OR
                         (MA_CustSuppCustomerOptions.Category = '07')
ORDER BY somma DESC

我有MA_SaleDocSummary.GoodsAmount的和和MA_SaleDoc.DocumentType的COUNT。但我遇到了问题......如果MA_SaleDoc.DocumentType='3407876',则必须将GoodsAmount减去总数。如何在此查询中实现此变体?

2 个答案:

答案 0 :(得分:0)

SUM(if(MA_SaleDoc.DocumentType ='3407876',0,MA_SaleDocSummary.GoodsAmount))

MySQL的那个

答案 1 :(得分:0)

如果您希望减去 DocumentType3407876,那么这可能适用于SQL Server

SUM(CASE WHEN MA_SaleDoc.DocumentType = '3407876' THEN (MA_SaleDocSummary.GoodsAmount * -1) ELSE MA_SaleDocSummary.GoodsAmount END)