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

时间:2019-03-01 16:34:12

标签: sql ms-access

假设我有这张桌子

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

3 个答案:

答案 0 :(得分:2)

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

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)

答案 1 :(得分:0)

您可以使用相关子查询:

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表示标识列顺序的标识列。

答案 2 :(得分:0)

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

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))