我有2个表,我拿着记录如下
查询为
Select BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description,
BMC.JCRS_Mem_Date,
BJCM.JCRS_Mast_Title
From Bus_MemberCourse BMC
Inner Join Bus_JourneymanCourseMaster BJCM
On BMC.JCRS_Mem_crs_Code = BJCM.JCRS_Mast_Code
Where BMC.JCRS_Mem_Completed = 1
And BMC.JCRS_Mem_mem_ID = 5010
Group By BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description,
BMC.JCRS_Mem_Date,
BJCM.JCRS_Mast_Title
但我想要的是我需要在Jcrs_mem_crs_code和Jcrs_mem_description上进行分组,如果这2列数据是常见的,那么我只想从这多个日期获取最新日期。即我只想选择该行并忽略其他行。
答案 0 :(得分:0)
您只想要MAX(date)
:
Select BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description,
MAX(BMC.JCRS_Mem_Date) as JCRS_Mem_Date,
BJCM.JCRS_Mast_Title
From Bus_MemberCourse BMC
Inner Join Bus_JourneymanCourseMaster BJCM
On BMC.JCRS_Mem_crs_Code = BJCM.JCRS_Mast_Code
Where BMC.JCRS_Mem_Completed = 1
And BMC.JCRS_Mem_mem_ID = 5010
Group By BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description,
BJCM.JCRS_Mast_Title
答案 1 :(得分:0)
您根本不需要Group by
(您的查询中没有进行任何聚合)。
这可以通过Row_Number()
窗口函数轻松完成,这两个列上的Partition
按日期排序:
;With Cte As
(
Select BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description,
BMC.JCRS_Mem_Date,
BJCM.JCRS_Mast_Title,
Row_Number() Over (Partition By BMC.JCRS_Mem_crs_Code,
BMC.JCRS_Mem_Description
Order By BMC.JCRS_Mem_Date Desc) As RN
From Bus_MemberCourse BMC
Inner Join Bus_JourneymanCourseMaster BJCM
On BMC.JCRS_Mem_crs_Code = BJCM.JCRS_Mast_Code
Where BMC.JCRS_Mem_Completed = 1
And BMC.JCRS_Mem_mem_ID = 5010
)
Select JCRS_Mem_crs_Code,
JCRS_Mem_Description,
JCRS_Mem_Date,
JCRS_Mast_Title
From Cte
Where RN = 1