累积字段基于ORDER字段而不是首次出现

时间:2014-06-23 09:12:14

标签: mysql sql select

我目前有这个events表:

id | user | country | when
---+------+---------+-----------------------
5  | 1    | my      | "2011-07-21 00:00:00"
19 | 1    | my      | "2014-04-02 18:00:00"
20 | 1    | my      | "2014-04-09 18:00:00"
29 | 1    | my      | "2011-09-27 15:00:00"
30 | 1    | my      | "2011-02-01 15:00:00"
31 | 1    | my      | "2012-05-12 19:00:00"
75 | 1    | my      | "2014-06-20 16:00:00"

在输出中,我需要获得user出现country的次数以及accumulated。为此,我使用此查询:

SELECT f.id, f.user, f.country, f.`when`, (
  SELECT COUNT(*) FROM events AS f2
  WHERE f2.country = f.country AND f2.user = f.user
) AS countrytimes, (
  SELECT count(*) FROM events AS f3
  WHERE f3.country = f.country AND f3.id <= f.id AND f3.user = f.user
  ORDER BY f.`when` DESC
) AS accumulated
FROM events AS f
WHERE f.user = 1
AND f.country = 'my'
ORDER BY f.`when` DESC

该查询的输出基于字段when,直到此处为止。问题是,累积的字段是基于所请求的usercountry的首次出现,而不是when字段。

id | user | country | when                  | countrytimes | accumulated
---+------+---------+-----------------------+--------------+-------------
75 | 1    | my      | "2014-06-20 16:00:00" | 7            | 7
20 | 1    | my      | "2014-04-09 18:00:00" | 7            | 3
19 | 1    | my      | "2014-04-02 18:00:00" | 7            | 2
31 | 1    | my      | "2012-05-12 19:00:00" | 7            | 6
29 | 1    | my      | "2011-09-27 15:00:00" | 7            | 4
5  | 1    | my      | "2011-07-21 00:00:00" | 7            | 1
30 | 1    | my      | "2011-02-01 15:00:00" | 7            | 5

表格和查询位于此 SQLFiddle

如何对其进行排序,以使when = 2011年2月1日的行获得accumulated = 1?

1 个答案:

答案 0 :(得分:0)

您只需将累积条件从f3.id <= f.id更改为f3.when <= f.when即可按日期而非ID进行累积;

SELECT f.id, f.user, f.country, f.when, (
  SELECT COUNT(*) FROM events AS f2
  WHERE f2.country = f.country AND f2.user = f.user
) AS countrytimes, (
  SELECT count(*) FROM events AS f3
  WHERE f3.country = f.country AND f3.when <= f.when AND f3.user = f.user
  ORDER BY f.`when` DESC
) AS accumulated
FROM events AS f
WHERE f.user = 1
AND f.country = 'my'
ORDER BY f.`when` DESC

An SQLfiddle to test with