在sql中,如何从相同ID记录的多个外键中获取最高的唯一主键记录

时间:2014-06-10 11:03:23

标签: sql sql-server c#-4.0

在我的项目中,我有一个存储过程。

ALTER procedure [dbo].[usp_SelectAllAspirantDetails]
as
begin

SELECT Distinct A.[AID]
      ,A.[Name]
      ,A.[Gender]
      ,A.[ContactNo]
      ,A.[EmailID]
      ,A.[SkillSet]
      ,A.[Experience]
      ,A.[CompanyName] 
      ,Aq.[Qualification]
      ,Aq.[InstituteName]
      ,Aq.[YearOfPass]
      ,Aq.[Percentage]  
      ,MAX(Aq.ID)
FROM [Aspirant] A FULL join AspirantQualification Aq ON A.AID=Aq.AID  
GROUP BY A.AID,A.[Name],A.[Gender],A.[ContactNo],A.[EmailID],A.[SkillSet],A.          
        [Experience],A.[CompanyName] ,Aq.[Qualification],Aq.[InstituteName] ,
        Aq.[YearOfPass],Aq.[Percentage]  
ORDER BY A.AID DESC      

在此Aspirant AID是主键,AspirantQualification是外键。我想从AspirantQualification获得最后输入的记录,如果我已经输入第10,inter,degree是我输入的资格。我希望该AID的学位记录显示在gridview中。

2 个答案:

答案 0 :(得分:0)

按Aq.ID DESC命令,A.AID DESC 会猜到我会做的伎俩 如果你只想要最新的记录,那么在选择

之后在开头添加前一个

答案 1 :(得分:0)

写为:

create  procedure [dbo].[usp_SelectAllAspirantDetails]
as
begin


;WITH CTE as
(
select AID,ID,Qualification,InstituteName,YearOfPass,Percentage,
       row_number () over (partition by AID order by ID desc) as rownum
from AspirantQualification
)
Select A.[AID]
      ,A.[Name]
      ,A.[Gender]
      ,A.[ContactNo]
      ,A.[EmailID]
      ,A.[SkillSet]
      ,A.[Experience]
      ,A.[CompanyName] 
      ,Aq.[Qualification]
      ,Aq.[InstituteName]
      ,Aq.[YearOfPass]
      ,Aq.[Percentage] 
      ,Aq.ID
FROM [Aspirant] A 
LEFT JOIN CTE Aq ON A.AID=Aq.AID and Aq.rownum = 1

end

点击此处Demo