2015-12-30 48 views
0

考慮有兩個表gamezone:表1和表2的Sql遊戲區查詢

在表1,當你在一個gamezone輸入數據被輸入:

表1


*user_Id* : integer type <br> 
*Time_of_entry* : timestamp type 

在表2中,僅當用戶進行交易(花費或收益)時才進入數據,並且它由以下字段組成:

表2


*user_Id* : integer type  <br>  
*Time_of_transaction* : timestamp type <br> 
*Money* : integer 

你需要找出每一天的最後MONEY爲每個不同的用戶,如果有在某一天沒有交易(即,有表2中的任何數據特定的日子和用戶,但是表1中有一個條目 - 即用戶在gamezone中輸入但沒有花錢),然後將前一天的錢作爲他今天的錢。

我該如何執行這種查詢?

樣本表已附於圖像enter image description here

+4

'mysql'和'oracle'是不同的** RDBMS **產品。 –

+0

你可以修復你目前難以閱讀的問題的格式嗎? –

+0

完成... @tim Biegeleisen –

回答

0

有了這個選擇,你會得到的,在表1,上表2中的最後一項爲用戶的每個用戶,如果沒有條目,0作爲貨幣價值。

SELECT 
    T1.user_Id, 
    T3.Time_of_Transaction, 
    ISNULL(t3.Money,0) as Money 
FROM Table1 as T1 
LEFT JOIN (
    SELECT 
     T2.user_Id, 
     T2.Time_of_Transaction, 
     T2.Money 
    FROM Table2 as T2 
    WHERE T2.Time_of_Transaction=(
     SELECT MAX(Time_of_Transaction) 
     FROM Table2 
     WHERE user_Id=T2.user_Id 
    ) 
) as T3 ON T1.user_id=T3.user_id 

它可以完善,但它應該工作。

編輯:要獲取每天一個條目,並在沒有某一天得到最後momeny交易的做法應該是更喜歡這種交易的情況下:

SELECT 
    user_Id, 
    Time_of_entry, 
    (
     -- Get the last money transaction of the user according to his last login 
     SELECT Money 
     FROM Table2 as T2 
     WHERE user_Id=T1.user_Id 
     AND Time_of_Transaction= (
      -- Get the last date with a money transacion according to his last login 
      SELECT MAX(Time_of_Transaction) 
      FROM Table2 
      WHERE user_Id=T2.user_Id 
      -- This has to be adjusted to filter the Time_of_Transaction according to the date and not hour. 
      AND CAST(Time_of_Transaction as Date)<=CAST(T1.Time_of_entry as Date) 
     ) 
    ) as Money 
FROM Table1 as T1 
+0

@Diveiveras ...這個解決方案中的T3是什麼? –

+0

@ShaktiKumar T3是在LEFT JOIN中使用的子選擇的別名。在左邊加入()後的選擇 – Doliveras

+0

@ Doliveras ..我的問題是......每天獲得每個用戶的最後一筆錢,如果他沒有在某一天花費任何錢,那麼考慮以前的錢作爲他的最後一筆錢 –