2013-10-01 47 views
0

這裏頂1是我的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

請檢查你的問題,並給予明確的方式 – SK2185

回答

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