我有一個包含客戶數據行的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查詢中對它們進行過濾?
您是否有意使'cost.saleid'有兩次?這可能會導致重複的條目? – DD84