[英]How to return dynamic table with Max Date
I keep a log where I enter Job, Description, TC Code, Units, Date Requested, and Requester. 在输入作业,描述,TC代码,单位,请求日期和请求者的位置保存日志。 From here I need to return each Job, along with each distinct TC code (which will continue to grow) and the rest of the information where the date requested is the Max Date. 从这里,我需要返回每个作业,以及每个不同的TC代码(它将继续增长)以及要求日期为“最大日期”的其余信息。
EX Log: EX日志:
Job Desc TC CODE Units Date Rqstr
17 MCD Days 5 4/1/19 Fred
20 BK Days 10 4/1/19 John
17 MCD Crew 8 4/2/19 Bob
33 WEN Days 10 4/1/19 Dave
40 ARB Crew 7 4/3/19 Jim
40 ARB Hours 10 4/3/19 Jim
17 MCD Days 10 4/5/19 Tim
17 MCD Con 5 4/5/19 Tim
20 BK Days 8 4/8/19 Tye
20 BK Crew 3 4/8/19 Tye
17 MCD Crew 5 4/8/19 Tim
I tried Row Number, but I can not really partition TC code because I need every distinct code, per job as well. 我尝试了行号,但是我不能真正地划分TC代码,因为每个工作也需要每个不同的代码。 Partitioning will only return distinct TC codes, and list the Jobs where the date is the max date 分区将仅返回不同的TC代码,并列出日期为最大日期的作业
select [Job],
[Description],
[TC Code],
[Units],
[Date Requested],
[Requestor]
from (Select [Job],
[Description],
[TC Code],
[Units],
[Date Requested],
[Requestor],
row_number() over(partition by [TC Code] order by [Date Requested]
desc) as rn
from [dbo].['VAR ADJ Log$']) as t
where rn = 1
The result I need: 我需要的结果:
I need to return every distinct TC Code with the latest date, per job. 我需要为每个作业返回每个具有最新日期的TC代码。 As you can see on Job 17 a new TC Code was introduced and added, and the Crew TC code was replaced with the most recent. 正如您在工作17上看到的那样,引入并添加了新的TC代码,并且Crew TC代码已被最新的TC代码取代。
Job Desc TC CODE Units Date Rqstr
17 MCD Days 10 4/5/19 Tim
17 MCD Crew 5 4/8/19 Tim
17 MCD Con 5 4/5/19 Tim
20 BK Days 8 4/8/19 Tye
20 BK Crew 3 4/8/19 Tye
33 WEN Days 10 4/1/19 Dave
40 ARB Crew 7 4/3/19 Jim
40 ARB Hours 10 4/3/19 Jim
Is this what you want? 这是你想要的吗?
select val.*
from [dbo].['VAR ADJ Log$'] val
where val.date = (select max(val2.date)
from [dbo].['VAR ADJ Log$'] val2
where val2.job = val.job and val2.[TC Code] = val2.[TC Code]
);
You can also do this with window functions (although there is probably no particular advantage). 您也可以使用窗口函数执行此操作(尽管可能没有特别的优势)。 This seems to be the logic you are asking for. 这似乎是您所要求的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.