DB:Mysql
我有一张表(tblSomething),其中包含以下记录:
现在我需要通过从此表中选择最新的唯一记录来过滤此记录。
结果应为:
在第二张图片中,2015年11月16日的乔和里娜无法使用。
您能告诉我如何编写查询来实现此目的。
答案 0 :(得分:2)
尝试以下查询:
ID1
内部查询为每个ID2
/ tlbSomething
对确定最近的日期。然后,通过仅保留每个ID1
/ ID2
对中具有此最新日期的记录来限制对整个{{1}}表的查询。
使用OP中的示例数据单击下面的链接以获取正在运行的演示。
答案 1 :(得分:0)
使用MAX
或str_to_date
SELECT *
FROM table t1
WHERE str_to_date(t1.date,'%m/%d/%Y')=(SELECT MAX(str_to_date(t2.date,'%m/%d/%Y'))
FROM table t2
WHERE t1.ID2 = t2.ID2)
答案 2 :(得分:0)
试试这个:
select t.username, t.date, t.value from MyTable t inner join ( select username, max(date) as MaxDate from MyTable group by username ) tm on t.username = tm.username and t.date = tm.MaxDate
参考:how do I query sql for a latest record date for each user
答案 3 :(得分:0)
CREATE TABLE #tblSomething
(ID1 int, ID2 int, Name1 varchar(55), Name2 varchar(55), date1 date, cost int, days int, somefield int);
INSERT INTO #tblSomething
(ID1, ID2, Name1, Name2, date1, cost, days, somefield)
VALUES
(330, 435, 'sn1', 'hello1', '2015-11-17', 500, 12, 34),
(404, 467, 'joe', 'rina', '2015-11-23', 600, 23, 22),
(404, 467, 'joe', 'rina', '2015-11-16', 700, 11, 123),
(404, 468, 'joe', 'tina', '2015-11-23', 800, 23, 41),
(404, 468, 'joe', 'tina', '2015-11-16', 789, 11, 43);
试试这个
with res as (select *,ROW_NUMBER() over(partition by ID1, ID2, Name1, Name2 order by ID1, ID2, Name1, Name2) as rn from #tblSomething)
select ID1, ID2, Name1, Name2, date1, cost, days, somefield from res where rn=1
输出