我在这里面临一个角落......
背景:
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)
但有些事情显然不在这里。
答案 0 :(得分: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;
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
)
答案 4 :(得分: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 )