2017-04-25 35 views
0

我有一個包含客戶數據行的DB2表。這用於確定客戶是否使用我們的服務節省了資金。較舊的記錄是觸發我們流程的購買,而較新的記錄是在他們再次購買同一產品後。期望的結果是看到一行包含他們最早的支付金額,他們的最新金額和兩行之間的差異,以驗證他們存錢。DB2將多個行選擇爲單個結果

的數據奠定了這樣

ID  Name  Product ID Sale ID  First Paid  Last Paid 
1  Mary  15   195   8    NULL 
2  Mary  15   195   NULL   3 
3  Bob  8    283   16    NULL 
4  Bob  8    283   NULL   11 

期望的結果是這個

Name  Sale ID Product ID  First Paid Last Paid Savings  
Mary  195  15    8   3   5 
Bob  283  8    16   11   5 

這是我所得到的,而不是

Name Sale ID Product ID  First Paid  Last Paid  Savings 
Mary 195  15    8    NULL   8 
Mary 195  15    NULL   3    -3 
Bob  283  8    16    NULL   16 
Bob  283  8    NULL   11   -11 

此查詢的結果用於來驅動一個更大的報告,以便將其作爲子查詢的一部分生成。

SELECT cost.name, cost.saleid, cost.productid, cost.saleid, 
cost.firstpaid, cost.lastpaid, sum(cost.firstpaid - cost.lastpaid) as savings 
from (
    select distinct saleid, max(name) as name, max(productid) as productid, 
    max(firstpaid) as firstpaid, max(lastpaid) as lastpaid) as cost 

我發現,我的大的查詢按預期工作,但這個最內層查詢返回的多行是一個具有客戶計算兩次時,他們應該只計算一次對結果產生負面影響。有沒有辦法在DB2中將這些值放入同一行,或者我是否需要撤回結果並在php代碼而不是SQL查詢中對它們進行過濾?

+0

您是否有意使'cost.saleid'有兩次?這可能會導致重複的條目? – DD84

回答

2

假設每個客戶的兩行,然後聚集似乎是一個正確的做法:

select Name, SaleID, ProductID, 
     sum(firstpaid) as firstpaid, sum(lastpaid) as lastpaid 
     sum(firstpaid) - sum(lastpaid) as savings 
from t 
group by Name, SaleID, ProductID; 

這適用於兩排以上。我不確定在有其他行時是否需要sum()min()max()avg()

+0

be carefull sum(firstpaid) - sum(lastpaid)如果sum(firstpaid)爲null或sum(lastpaid)爲null,則返回null。也許你可以使用sum(ifnull(firstpaid,0))來代替其他和;) – Esperento57