给定一个名为Messages的数据库表,其中包含以下列: -
MessageID, FromUser, ToUser, Message, DateTime
我想写一个SQL查询,为“FromUser”列选择不同的值,但我也想要DateTime排序的值。
基本上,查询如:
SELECT * FROM Messages WHERE ToUser='1' ORDER BY DateTime DESC
然后,用以下内容选择不同的FromUser:
SELECT DISTINCT FromUser FROM Messages WHERE ToUser='1'
同时,维护上一次查询的排序。
我尝试使用嵌套查询并遇到问题,因为您无法在内部查询中使用ORDER BY。
基本上,我希望查询的语法表示(这是无效的但是......):
SELECT DISTINCT FromUser FROM Messages WHERE ToUser=1 AND FromUser IN
(SELECT * FROM Messages WHERE ToUser=1 ORDER BY DateTime DESC)
答案 0 :(得分:2)
我猜这就是你需要的:
;WITH CTE AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY [FromUser] ORDER BY [DateTime] DESC) RN
FROM [Messages]
WHERE ToUser='1'
)
SELECT *
FROM CTE
WHERE RN = 1
答案 1 :(得分:0)
因此,请在DateTime
语句中加入select
,或者使用MAX()
进行分组,或者使用其中一个聚合函数,例如 Select fromuser, datetime
from messages
where touser = '1'
group by
fromuser, datetime
order by
fromuser, datetime
,如:
Select fromuser, max(datetime) as max_datetime
from messages
where touser = '1'
group by
fromuser
或
{{1}}
答案 2 :(得分:0)
您将为每个FromUser设置多个时间戳。我将假设您要为每个时间戳使用最后一个时间戳。
select *
from Messages join
(select fromuser, MAX(datetime) as lastdate from Messages
group by FromUser) as abb1 on abb1.FromUser = messages.FromUser and abb1.lastdate = messages.Datetime
where ToUser = '1'
order by Datetime desc
答案 3 :(得分:0)
SELECT DISTINCT [Messages].[FromUser] FROM (
SELECT [FromUser] as [FromUser], MAX(DateTime) as [Date]
FROM [Messages]
GROUP BY [FromUser]) as [Messages]
答案 4 :(得分:0)
另一种方式;
select * from
(
select *, max(DateTime) over (partition by FromUser) newest
from Messages
) T
where DateTime = newest
(如果同一个人的日期相同,则为n行)