[英]SQL - How to select data row with Maximum value within a specific column? [Part 2]
[英]SQL - How to select data row with Maximum value within a specific column?
在准備創建視圖時測試 SQL 查詢的過程中,我第一次想到了這個公式
select a.SchID as [SchID], b.CourseID as [CourseID], a.EmpNo as [EmpNo],
b.ActStartDate as [ActStartDate], a.ValidTo as [ValidTo]
from [SQL3].[dbo].[Training_Record] a inner join
(select z.schid, z.CourseID as [CourseID],max(z.ActStartDate) as [ActStartDate]
from [SQL3].[dbo].[Training_Schedule] z group by z.SchID, z.CourseID)as b
on a.SchID = b.SchID
-- to test data content
where EmpNo = '141281' and CourseID = '22'
結果給了我 2 行:
| SchID | CourseID | EmpNo | ActStartDate | ValidTo |
--------------------------------------------------------------------------------
| 5000 | 22 | 14000 | 2018-06-11 00:00:00.000 | 2018-12-10 00:00:00.000 |
| 5022 | 22 | 14000 | 2018-08-08 00:00:00.000 | 2019-02-07 00:00:00.000 |
我想要第 2 行,其 ActStartDate 是最大的,是唯一出現的行。
| SchID | CourseID | EmpNo | ActStartDate | ValidTo |
--------------------------------------------------------------------------------
| 5022 | 22 | 14000 | 2018-08-08 00:00:00.000 | 2019-02-07 00:00:00.000 |
但是由於 SchID 具有不同的編號,它最終注冊為單獨的條目。 SchID 是這兩個表中唯一共享的列,那么我如何告訴 SQL 忽略 SchID 讀取並僅顯示第二行?
您可以嘗試以下 - 使用子查詢
select a.SchID as [SchID], b.CourseID as [CourseID], a.EmpNo as [EmpNo],
b.ActStartDate as [ActStartDate], a.ValidTo as [ValidTo]
from [SQL3].[dbo].[Training_Record] a
inner join
(select z.schid, z.CourseID as [CourseID],max(z.ActStartDate) as [ActStartDate]
from [SQL3].[dbo].[Training_Schedule] z group by z.CourseID)as b
on a.SchID = b.SchID
where EmpNo = '141281' and CourseID = '22' and
b.ActStartDate in (select max([ActStartDate]) from [SQL3].[dbo].[Training_Schedule] z1 where b.courseid=z1.courseid group by z1.courseid)
或者您可以嘗試使用row_number()
select * from
(
select a.SchID as [SchID], b.CourseID as [CourseID], a.EmpNo as [EmpNo],
b.ActStartDate as [ActStartDate], a.ValidTo as [ValidTo],row_number() over(partition by b.courseid order by b.ActStartDate desc) as rn
from [SQL3].[dbo].[Training_Record] a inner join
(select z.schid, z.CourseID as [CourseID],max(z.ActStartDate) as [ActStartDate]
from [SQL3].[dbo].[Training_Schedule] z group by z.SchID, z.CourseID)as b
on a.SchID = b.SchID
-- to test data content
where EmpNo = '141281' and CourseID = '22'
)A where rn=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.