2017-05-16 46 views
1

我提供了一個我的數據外觀示例。餐桌上充滿了客房餘量不足的情況。每天都會生成一份報告,並帶有負餘額。報告使用新的reportdate導入到我的表格中。有沒有一種方法可以實現以下目標:每天重複清理數據

返回customerID達到找到的最大ending_amount的第一個日期的行。這意味着如果customerid在20天的數據第10天達到-3.50的ending_amount,我希望它在20天的第10天只返回一行數據,而忽略與該customerid相關的其他19天的數據。

注:

** - **客戶ID是一個獨特的價值。

** - **當起始金額爲<> ending_amount時,表示該帳戶餘額發生了變化。

是否有無論如何,我可以通過清理這張表,如何或通過編寫查詢來實現我的目標?

謝謝你的幫助。

Expected Data output 

reportdate customerid starting_amount ending_amount 
    1/1/17  2   -0.00   -0.50 
    1/3/17  3   -0.50   -1.00 
    1/4/17  1   -0.50   -3.27 
    1/4/17  4   -0.00   -0.50 
    1/4/17  5   -0.50   -1.32 

的樣本數據

tbl_accountchange 

reportdate customerid starting_amount ending_amount 
    1/1/17  1    -0.00   -0.50 
    1/1/17  2    -0.00   -0.50 
    1/2/17  1    -0.50   -0.50 
    1/2/17  2    -0.50   -0.50 
    1/2/17  3    -0.00   -0.50 
    1/3/17  1    -0.50   -0.50 
    1/3/17  2    -0.50   -0.50 
    1/3/17  3    -0.50   -1.00 
    1/3/17  4    -0.00   -0.50 
    1/3/17  5    -0.00   -0.50 
    1/4/17  1    -0.50   -3.27 
    1/4/17  2    -0.50   -0.50 
    1/4/17  3    -1.00   -1.00 
    1/4/17  4    -0.50   -0.50 
    1/4/17  5    -0.50   -1.32   
+0

因此,在您的數據示例中,預期的輸出是什麼? –

+0

你好,我已經添加了我的期望輸出。基本上,我想返回第一個reportdate上的每一行,該帳戶達到了表中找到的最大結餘餘額。客戶ID不應該多於一次返回。 –

回答

0

要了解每個客戶的最大期末數

select customerId, max(ending_amount) max_ea 
from tbl_accountchange 
where reportdate between '2017-01-01' and '2017-01-20' 
group by 1 

,查找出現爲每一個客戶這個值的最早日期:

select a.customerId, min(reportdate) rd 
from tbl_accountchange a 
join (
    -- above query 
) b on a.customerId = b.customerId 
    and a.ending_amount = max_ea 
group by 1 

The整個查詢:

select t.* 
from tbl_accountchange t 
join (select a.customerId, min(reportdate) rd 
    from tbl_accountchange a 
    join (
     select customerId, max(ending_amount) max_ea 
     from tbl_accountchange 
     where reportdate between '2017-01-01' and '2017-01-20' 
     group by 1 
    ) b on a.customerId = b.customerId 
    and a.ending_amount = max_ea 
    where reportdate between '2017-01-01' and '2017-01-20') c 
    on t.customerId = c.customerId 
    and t.reportdate = c.reportdate 

查詢都不是相關的,所以應該對大數據集執行,甚至相當不錯。

請注意日期範圍條件必須在兩個子查詢中。

+0

我在將表格混爲c之前添加了另一個缺口。我收到的回覆是欄目列表中的customerid含糊不清? –

+0

@EdwardKo當你遇到這樣的錯誤時,你需要確定你選擇的列來自哪個表格。在這種情況下,我通過在列名之前加上'a.'來解決它 - 請參閱編輯答案。添加括號不應該是必要的。 (順便提一下,我在巴士上翻閱了這個查詢,所以很可能會錯過這樣的小細節) – Bohemian