[英]Pick Latest Entry of a specific ID from table
I have the following table我有下表
Report Number![]() |
Department![]() |
Date![]() |
Price![]() |
---|---|---|---|
77e1117e-a248-4781-866f-704bea114d11 ![]() |
Dep.![]() ![]() |
2022-06-13 10:12:42.000 ![]() |
685.10 ![]() |
77e1117e-a248-4781-866f-704bea114d11 ![]() |
Dep.![]() ![]() |
2022-06-13 10:12:42.000 ![]() |
0.19 ![]() |
a34f8425-c64f-47a9-b947-49e7d2fd5bba ![]() |
Dep.![]() ![]() |
2022-06-13 13:16:45.000 ![]() |
102.45 ![]() |
a34f8425-c64f-47a9-b947-49e7d2fd5bba ![]() |
Dep.![]() ![]() |
2022-06-13 13:16:45.000 ![]() |
427.13 ![]() |
h94e8421-h79j-25q9-n478-58w7f2af6ffe ![]() |
Dep.02 ![]() |
2022-06-13 13:16:45.000 ![]() |
98.98 ![]() |
h94e8421-h79j-25q9-n478-58w7f2af6ffe ![]() |
Dep.![]() ![]() |
2022-06-13 13:16:45.000 ![]() |
500.50 ![]() |
These are two reports, each with two entries, generated at a different time and yielding a different price.这是两个报告,每个都有两个条目,在不同的时间生成并产生不同的价格。
I would like to have a script/code that can automatically choose the latest date and return the sum of prices corresponding to that report number per department.我想要一个脚本/代码,可以自动选择最新日期并返回与每个部门的报告编号相对应的价格总和。
The output should be something like that:输出应该是这样的:
Report Number![]() |
Department![]() |
Date![]() |
Price![]() |
---|---|---|---|
a34f8425-c64f-47a9-b947-49e7d2fd5bba ![]() |
Dep.![]() ![]() |
2022-06-13 13:16:45.000 ![]() |
529.58 ![]() |
h94e8421-h79j-25q9-n478-58w7f2af6ffe ![]() |
Dep.![]() ![]() |
2022-06-13 13:16:45.000 ![]() |
599.48 ![]() |
Select ReviewNr, [Date], Sum(Price)
from myTable
where ReviewNr in (select top(1) reviewNr from myTable order by [Date] desc)
group by ReviewNr, [Date];
Something like this:像这样的东西:
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY Date DESC ) AS RowNumber,
SUM(Price) OVER (PARTITION BY ProductId ) PriceSum
FROM WhateverTableItIs
) T
WHERE RowNumber = 1
(Why have you posted HTML when your question is about SQL?!) (当您的问题是关于 SQL 时,为什么要发布 HTML?!)
Seems like you can aggregate the rows for each ReportNumber
then use ROW_NUMBER
by date似乎您可以汇总每个
ReportNumber
的行,然后按日期使用ROW_NUMBER
SELECT
Department,
ReportNumber,
Date,
Price
FROM (
SELECT
Department,
ReportNumber,
Date,
SUM(Price) Price,
ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Date DESC) rn
FROM YourTable t
GROUP BY
Department,
Date,
ReportNumber
) t
WHERE rn = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.