Sql游戏区域查询

时间:2015-12-30 06:47:10

标签: mysql sql oracle

考虑一个有两个表的gamezone:Table1和Table2

在表1中,只要您进入游戏区域,就会输入数据:

表1

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

在Table2中,只有当用户进行交易(花钱或赚钱)时才会输入数据,并且它包含以下字段:

表2

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

您需要找出每个不同用户每天的最后一个MONY,如果某一天没有交易(也就是说,Table2中没有特定日期和用户的数据,但是有一个条目表1 - 即用户进入游戏区但没有花钱)然后将前一天的钱视为当天的钱。

我将如何执行此类查询?

示例表已附加为图像enter image description here

1 个答案:

答案 0 :(得分:0)

使用此SELECT,对于Table1中的每个用户,您将获得Table2上该用户的最后一个条目,如果没有条目,则为0作为Money值。

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