SQL Server GROUPING和DISTINCT

时间:2012-02-21 08:22:57

标签: sql sql-server-2008-r2

您好我的公司前雇员所做的选择陈述非常复杂 它的作用是返回申请人申请的所有工作清单。 查询工作正常,但我只需要应用唯一的作业。我在使用DISTINCT或GROUP BY时遇到问题。 重复发生是因为与工作和申请人相关的表有重复,我无法做任何事情。所以有人能帮我解决这个问题吗? PS:请不要责怪Query结构不是我的。谢谢!

         SELECT 
                J.JobsID, 
                J.JobsHeader, 
                I.IndustryName,
                J.JobDescription, 
                J.JobBreif, 
                J.JobRequirement, 
                J.JobLocation, 
                (SELECT CASE WHEN J.HideSalary = 1 THEN 'hidden' ELSE J.Salary END) AS 'Salary',
                J.HideSalary, 
                (SELECT CASE WHEN J.HideCompanyName = 1 THEN 'hidden' ELSE COMP.CompanyName END) AS 'CompanyName',
                J.HideCompanyName, 
                J.CurrentStatus, 
                J.ExperienceInMonth, 
                J.ExperienceInYear, 
                Q.QualificationName, 
                J.HourID, 
                J.Age, 
            J.Gender, 
            L.CityName, 
            J.UAENationals, 
            J.SeniorExecutive, 
            J.StartDate, 
            J.EndDate, 
            S.SpecizationName, 
            CIRT.SpecizationName AS 'CirtificationName', 
            J.AvailType,
            J.CreatedOn, 
            J.CreatedBy, 
            J.ModifiedOn, 
            J.ModifiedBy,
            N.CountryName,
            --ETJA.CreatedOn AS 'AppliedOn',
            '12/01/2012' AS 'AppliedOn',
            ETJA.JobsId AS 'AppliedJobId'


        FROM dbo.EmployeeToJobsApplied ETJA 
        INNER JOIN dbo.Jobs J ON J.JobsID = ETJA.JobsId
        INNER JOIN dbo.Employers COMP ON J.CompanyID = COMP.EmployerId
        LEFT JOIN dbo.Experience E ON J.ExperienceInYear = E.ExperienceID
        LEFT JOIN dbo.Industry I ON J.JobIndustryId = I.IndustryID
        LEFT JOIN dbo.Location L ON J.LocationID = L.CityId
        LEFT JOIN dbo.Qualification Q  ON J.QualificationID = Q.QualificationID
        LEFT JOIN dbo.Nation N ON J.CountryID = N.CountryID
        LEFT JOIN dbo.Specization S  ON J.SpecilizationId = S.SpecizationID
        LEFT JOIN dbo.Specization CIRT ON J.CirtificationId  = CIRT.SpecizationID
        WHERE ETJA.Applied = 1 AND ETJA.EmployeeId=1

1 个答案:

答案 0 :(得分:0)

您可以在现有查询中添加DISTINCT,但我怀疑有几列选择始终是唯一的(例如,CreatedOn,ModifiedOn)。所以,它不太可能有所帮助。

您必须创建一个只返回当前列的子集的查询。从最低限度开始,验证它是否为您提供了正确的作业列表。然后开始添加其他列 - 如果它停止返回不同的作业,那么您将无法在此查询中使用该列。

SELECT DISTINCT
    J.JobsID,
    J.JobsHeader 
FROM dbo.EmployeeToJobsApplied ETJA 
    INNER JOIN dbo.Jobs J ON J.JobsID = ETJA.JobsId
WHERE ETJA.Applied = 1 AND ETJA.EmployeeId=1