繁体   English   中英

如何使用sql为列的每个唯一值仅选择第一行

[英]How to select only the first rows for each unique value of a column with sql

假设我有这张桌子

name | year | month | val 
-----+------+-------+------
user1| 2019 | 02    | YES
user1| 2019 | 01    | NO
user2| 2019 | 02    | YES
user3| 2019 | 02    | NO

我想为每个用户获取最后的答案(MAX(年)和MAX(月)

name | val 
-----+-----
user1| YES
user2| YES
user3| NO

我的实际SQL请求:

SELECT DISTINCT name, val 
FROM answer AS sf 
LEFT JOIN user AS u ON u.id_user = sf.id_user 
WHERE sf.id_feedback = 1  
ORDER BY name

我正在使用Microsoft Access

第一组获得每个用户的最大日期,然后加入:

select a.name, a.val 
from answer as a inner join (
  select name, max(dateserial(year, month, 1)) as maxdate
  from answer
  group by name
) as g on g.name = a.name and g.maxdate = dateserial(a.year, a.month, 1)

如果yearmonth列为“文本”,则:

select a.name, a.val 
from answer as a inner join (
  select name, max(year & month) as maxdate
  from answer
  group by name
) as g on g.name = a.name and g.maxdate = (a.year & a.month)

您可以使用相关子查询:

select t.name, t.val
from table t 
where t.pk = (select top 1 t1.pk
              from table t1
              where t1.name = t.name
              order by t1.year desc, t1.month desc
             );

pk表示标识列的标识列。

这是使用相关子查询的另一种方法:

select a.name, a.val from answer a
where not exists 
(select 1 from answer b where a.name = b.name and a.year < b.year and a.month < b.month)

编辑:下面的代码更正,以解决年份字段匹配但月份字段不同的情况:(感谢@ Scorpioo590)

select a.name, a.val from answer a
where not exists 
(select 1 from answer b where a.name = b.name and (a.year < b.year or (a.year = b.year and a.month < b.month)))

或者,使用dateserial

select a.name, a.val from answer a
where not exists 
(select 1 from answer b where a.name = b.name and dateserial(a.year,a.month,1) < dateserial(b.year,b.month,1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM