以下是我的SELECT语句的一小部分:
SELECT CASE WHEN I.IsSimCheckout=1 THEN
SUM(DISTINCT SalePrice) ELSE SUM(SalePrice) END
FROM InvoiceDetail TD WHERE TD.InvoiceID = D.InvoiceID
我想做的是:
SELECT CASE WHEN I.IsSimCheckout=1 THEN
SUM(TOP 1 SalePrice ORDER BY SalePrice) + SUM(TOP 1 SalePrice ORDER BY SalePrice DESC) ELSE SUM(SalePrice) END
FROM InvoiceDetail TD WHERE TD.InvoiceID = D.InvoiceID
显然,我知道后面的SQL不会编译。但基本上,我想要做的是,如果I.IsSimCheckout等于1,那么我想将最高销售价格和最低销售价格加在一起,而不是将所有这些加在一起。希望我想要做的事情有道理并且很明确。
我正在使用SQL Server 2008。
答案 0 :(得分:0)
SELECT
....
FROM InvoiceDetail TD
OUTER APPLY
(
SELECT TOP 1 SalePrice
FROM D(?)
WHERE TD.InvoiceID = D.InvoiceID
ORDER BY SalePrice ASC
) LP
OUTER APPLY
(
SELECT TOP 1 SalePrice
FROM D(?)
WHERE TD.InvoiceID = D.InvoiceID
ORDER BY SalePrice DESC
) HP
WHERE TD.InvoiceID = D.InvoiceID
这是一般的想法。我将为您留下SELECT语句。
答案 1 :(得分:0)
您可以使用groupby
进行以下操作 select
case when I.IsSimCheckout=1 then max(id.SalePrice)+min(id.SalePrice)
else sum(id.SalePrice) as result
from Invoice I join InvoiceDetail ID on I.InvoiceID=Id.InvoiceID
group by i.InvoiceID, id.InvoiceID, I.IsSimCheckout