2

我正面临这里的一个角落...

的背景:

TABLE myrecord (
 id     int         # primary key
 name   varchar(32) # test name
 d_when varchar(8)  # date in yyyymmdd string format
) 

内容:

id    name     d_when
100   Alan     20110201
101   Dave     20110304
102   Alan     20121123
103   Alan     20131001
104   Dave     20131002
105   Bob      20131004
106   Mike     20131101

用外行的话来说,我想弄清楚谁是“回归者”以及他最后一次(即“倒数第二次”)访问是什么时候。像过分热情的东西:

SELECT SECOND_MAX(id), CORRESPONDING(d_when) 
FROM myrecord 
GROUP BY name 
HAVING count(name)>1;

预期结果:

101   Dave     20110304 
102   Alan     20121123

到目前为止,我尝试了以下方法。

SELECT T1.id, t1.name, T1.d_when 
FROM myrecord t1 
WHERE id IN (SELECT MAX(id), 
    COUNT(id) cn 
    WHERE cn>1 
    ORDER BY d_when DESC)

但显然有些东西不在这里。

4

5 回答 5

3

这是一种方法...

SELECT x.* 
  FROM my_table x 
  JOIN my_table y 
    ON y.name=x.name 
   AND y.d_when >= x.d_when 
 GROUP 
    BY x.name 
     , x.d_when 
HAVING COUNT(*) = 2;
于 2013-07-06T08:47:17.433 回答
2

为什么倒数第二个 id 是必需的?

如果不是:

SELECT MAX(id), name, MAX(d_when)
FROM myrecord
    GROUP BY name 
    HAVING count(name)>1

如果是:

SELECT name, max(id), max(d_when)
FROM myrecord
WHERE 
-- get only the names that have more then one occurrence
name in (
    SELECT name
    FROM myrecord
    GROUP BY name
    HAVING COUNT(*) > 1
)
-- filter out the max id's
AND id NOT IN(
    SELECT max(id)
    FROM myrecord
    GROUP BY name
)
GROUP BY name

甚至更好(感谢@Andomar 的提及):

SELECT name, max(id), max(d_when)
FROM myrecord
WHERE 
-- filter out the max id's, this will also filter out those with one record
AND id NOT IN(
    SELECT max(id)
    FROM myrecord
    GROUP BY name
)
GROUP BY name
于 2013-07-06T07:53:30.610 回答
2

在 MySQL 中,用于检索所有第二次访问的人及其第二次访问的日期。

询问:

SELECT *
FROM
(
SELECT
   @ID:=CASE WHEN @Name <> Name THEN 1 ELSE @ID+1 END AS rn,
   @Name:=Name AS Name,
   ID, d_when
FROM
  (SELECT ID, Name, d_when
   FROM myrecord
   ORDER BY Name asc, d_when asc
  ) rec1,   (SELECT @ID:= 0) rec1_id, (SELECT @Name:= 0) rec1_nm
) rec
where rec.rn=2

输出:

rn  Name    ID  d_when
2   Dave    104 20131002
2   Alan    102 20121123
于 2013-07-06T08:28:35.590 回答
1

假设id列随时间上升,您可以选择每个名称的第二高d_when,例如:

select  name
,       d_when
from    YourTable yt1
where   id in
        (
        select  max(id)
        from    YourTable yt2
        where   id not in
                (
                select  max(id)
                from    YourTable yt3
                group by
                        name
                )
        group by
                name
        )
于 2013-07-06T07:51:30.683 回答
0
select * from 
myrecord
where id in (
    SELECT max(id)
    FROM myrecord 
    WHERE id not in (SELECT MAX(id)
        FROM myrecord   
        GROUP BY name 
        HAVING count(name)>1)
    group by name )
于 2013-07-06T07:45:21.447 回答