0

这是我的 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,那么我想将最高的 saleprice 和最低的 saleprice 加在一起,而不是把它们加在一起。希望我正在尝试做的事情是有意义的并且是明确的。

我正在使用 SQL Server 2008。

4

2 回答 2

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 语句。

于 2013-10-01T06:38:42.797 回答
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
于 2013-10-01T06:47:42.513 回答