我有以下查询:
SELECT dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
CASE
WHEN io1.Code = '33' THEN SUM(idd.Qty)
ELSE SUM(0)
END AS Qty_BackSale,
CASE
WHEN io1.Code = '41' THEN SUM(idd.Qty)
ELSE SUM(0)
END AS Qty_Stock
FROM dbo.saleDocuments
INNER JOIN dbo.saleDocumentDetails
ON dbo.saleDocuments.ID = dbo.saleDocumentDetails.DocumentID
LEFT OUTER JOIN dbo.invDocumentDetails AS idd
ON dbo.saleDocumentDetails.ID = idd.saleDocumentDetailID
LEFT OUTER JOIN dbo.invDocuments AS id2
ON id2.ID = idd.invDocumentID
LEFT JOIN dbo.invOperations AS io1
ON (io1.ID = id2.invOperationID)
WHERE (dbo.saleDocumentDetails.ID = 1295617)
GROUP BY
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
io1.Code
结果是:
我想实现:
我该如何更改查询?
答案 0 :(得分:1)
将SUM()
语句中的CASE
移到CASE
之外:
SELECT
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
SUM(CASE
WHEN io1.Code = '33' THEN idd.Qty
ELSE 0
END) AS Qty_BackSale,
SUM(CASE
WHEN io1.Code = '41' THEN idd.Qty
ELSE 0
END) AS Qty_Stock
FROM
dbo.saleDocuments
INNER JOIN dbo.saleDocumentDetails
ON dbo.saleDocuments.ID = dbo.saleDocumentDetails.DocumentID
LEFT OUTER JOIN dbo.invDocumentDetails AS idd
ON dbo.saleDocumentDetails.ID = idd.saleDocumentDetailID
LEFT OUTER JOIN dbo.invDocuments AS id2
ON id2.ID = idd.invDocumentID
LEFT JOIN dbo.invOperations AS io1
ON (io1.ID = id2.invOperationID)
WHERE
(dbo.saleDocumentDetails.ID = 1295617)
GROUP BY
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
io1.Code;
答案 1 :(得分:1)
如前所述JRLambert,将SUM()
移到CASE
之外,并从io1.Code
移除GROUP BY
答案 2 :(得分:0)
您是否尝试过按dbo.saleDocumentDetails.ID删除群组?