简体   繁体   English

选择忽略一个字段的不同值

[英]Select distinct values ignoring one field

I have a table similar to this 我有一张与此类似的桌子

Table(Id int, PropertyId int, UserId int, AccesedOn datetime)

So the table can have value for one property for one user, but different times. 因此,该表可以为一个用户的一个属性值,但时间不同。

Eg.
1,100,5, 2012-10-16 16:24:48
2,100,5, 2012-10-17 11:22:00
3,100,5, 2012-10-18 17:10:05

What I am trying here is to select distinct properties for specific user, but order by most recent access time. 我在这里尝试的是为特定用户选择不同的属性,但是按最近的访问时间排序。

Also I am joining this table to three other tables which result in providing duplicate values. 另外,我将此表加入到其他三个表中,从而提供了重复的值。 Therefore I have to use DISTINCT command. 因此,我必须使用DISTINCT命令。

Problem I have is since I doing the orderby AccesedOn , it need to appear on select statement which doesn't brings the distinct values since the AccesedOn column have different values. orderby AccesedOn问题是因为我在执行orderby AccesedOn ,它需要出现在select语句中,该语句不会带来不同的值,因为AccesedOn列具有不同的值。

For above example it should return only 3,100,5, 2012-10-18 17:10:05 对于上面的示例,它应该仅返回3,100,5, 2012-10-18 17:10:05

Any suggestions to overcome this? 有什么建议可以克服吗?

;WITH CTE as(
select *,ROW_NUMBER() over (partition by PropertyId,UserId  order by AccesedOn desc) as rn
from table1)

select * from CTE where rn=1

It is more likely that you need a subselect than that you need a distinct for this. 为此,您可能需要一个子选择而不是一个单独的选择。

select * 
from Table A
where AccessedOn in
  (Select max(AccessedOn) from table B where A.UserId = B.UserId)

Instead of using DISTINCT , you can use MAX() and group by the rest of the columns 除了使用DISTINCT ,还可以使用MAX()并按其余列进行分组

Select Id, PropertyId, UserId, MAX(AccesedOn)
From Table t
group by Id, PropertyId, UserId

This should give you the results you are looking for. 这应该为您提供所需的结果。

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

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