查询Sqlite,仅为每个用户

时间:2016-11-17 07:50:10

标签: sqlite

我有一个关于Sqlite的复杂查询要运行。请考虑下表。

对于每个userID和BatchID以及状态总和,我需要三条最新记录。我还需要计算每个结果的记录数。

例如,假设用户ID U6TH16003只有1条记录,则记录计数为1.用户U6TH15001有7条记录,只考虑3条最新记录,并为用户的3条最新记录添加状态字段给出2,并且考虑状态字段总和的记录总数为3。

Date        UserID      Status
2016-11-14  U6TH16001   0   
2016-11-17  U6TH16001   0   
2016-11-07  U6TH16001   1   
2016-11-01  U6TH16001   0   
2016-10-20  U6TH16002   1   
2016-10-15  U6TH16002   1   
2016-10-10  U6TH16002   1   
2016-11-14  U6TH16003   1   
2016-11-17  U6TH15001   1   
2016-11-14  U6TH15001   0   
2016-11-07  U6TH15001   1   
2016-11-01  U6TH15001   0   
2016-10-28  U6TH15001   1   
2016-10-23  U6TH15001   1   
2016-10-15  U6TH15001   1   

上表所需的输出如下:

UserID          Sum(Status)     NumberOfRecords
U6TH16001       1               3
U6TH16002       3               3
U6TH16003       1               1
U6TH15001       2               3

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先,获取所有用户ID:

SELECT DISTINCT UserID FROM MyTable;

然后,对于每个此类用户ID,通过按日期对该用户的记录进行排序,并选择第三个日期来确定我们要处理的最小日期:

SELECT UserID,
       (SELECT Date
        FROM MyTable
        WHERE UserID = Users.UserID
        ORDER BY Date DESC
        LIMIT 1 OFFSET 2
       ) AS MinDate
FROM (SELECT DISTINCT UserID
      FROM MyTable
     ) AS Users;
UserID     MinDate
U6TH16001  2016-11-07
U6TH16002  2016-10-10
U6TH16003  NULL
U6TH15001  2016-11-07

然后我们可以将这些值与原始表连接起来,只获取所需的记录,最后对它们进行聚合:

SELECT MyTable.UserID,
       SUM(Status),
       COUNT(*)
FROM MyTable
JOIN (SELECT UserID,
             (SELECT Date
              FROM MyTable
              WHERE UserID = Users.UserID
              ORDER BY Date DESC
              LIMIT 1 OFFSET 2
             ) AS MinDate
      FROM (SELECT DISTINCT UserID
            FROM MyTable
           ) AS Users
     ) AS MinDates
     ON MyTable.UserID = MinDates.UserID
    AND MyTable.Date  >= IFNULL(MinDates.MinDate, 0)
GROUP BY MyTable.UserID;