gpt4 book ai didi

sql - 从 SQL 中的值列表中获取第一个值

转载 作者:行者123 更新时间:2023-12-01 21:56:55 27 4
gpt4 key购买 nike

我有下表

ID  Name    Activity date   total time

1 AB 1/10/2015 209

1 AB 1/11/2015 1234

1 AB 1/12/2015 10

2 CD 1/10/2015 2347

2 CD 1/11/2015 0

2 CD 1/12/2015 0

2 CD 1/13/2015 5

3 EF 1/10/2015 53

3 EF 1/11/2015 14

4 XY 1/11/2015 76

我需要以下结果

ID  Name    Activity date   total time

1 AB 1/10/2015 209

2 CD 1/10/2015 2347

3 EF 1/10/2015 53

4 XY 1/11/2015 76

基本上,我需要所有名称的第一个值,我使用了以下查询,但名称值为空白

SELECT distinct(Id),
FIRST_VALUE(Name) OVER (ORDER BY Id Asc) AS Name,
FIRST_VALUE(ActivityDate) OVER (ORDER BY Id Asc) AS Date,
FIRST_VALUE(TimeInQueue) OVER (ORDER BY Id Asc) AS Totaltime
FROM Historytable
GROUP BY Id,ActivityDate,Name

最佳答案

使用窗口函数

SELECT ID,
NAME,
[Activity date],
total time
FROM (SELECT Row_number() OVER(partition BY Id ORDER BY [Activity date]) Rn,
ID,
NAME,
[Activity date],
[total time] from yourtable) A
WHERE rn = 1

或查找每个id最短[事件日期]日期,并使用Id[将结果连接回表中事件日期]

SELECT a.ID,
a.NAME,
a.[Activity date],
a.[total time]
FROM yourtable A
JOIN (SELECT Min([Activity date]) [Activity date],
ID
FROM yourtable) B
ON a.id = b.id
AND a.[Activity date] = b.[Activity date]

关于sql - 从 SQL 中的值列表中获取第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913412/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com