简体   繁体   中英

Exclude row from select statement if it meets certain condition

I have an ID column in a table with employee ID strings as well as a column with the termination date of the employee. If the employee is still active it is a null value.

The problem here is that the employee ID's can be in two formats. If the employee is filled in more than one position in the company there will be a letter at the last index of their employee ID string. Example.

05214

05214A

If at least one of the termination dates associated with one of the above ID's is null then I want to exclude it from the select because it means that they are still active in at least one position.

This is the layout of the statement that I have now without the added functionality.

SELECT DISTINCT p.[hr_pe_id] AS ID,
                i.[SSN] AS SSN, 
                p.[emp_f_name] AS fname, 
                p.[emp_l_name] AS lname, 
                p.[term_dt] AS termdate
FROM [dbo].[InsurancePremiums] i 
INNER JOIN [production_finance].[dbo].[hr_pe_mstr] p
ON (i.[SSN] = p.[hr_pe_ssn])
WHERE(p.[term_dt] IS NOT NULL)

I think this is what you want. NB the "_" character is a sql wildcard for any single character match.

SELECT DISTINCT
  p.[hr_pe_id] AS ID,
  i.[SSN] AS SSN,
  p.[emp_f_name] AS fname,
  p.[emp_l_name] AS lname,
  p.[term_dt] AS termdate
FROM
  [dbo].[InsurancePremiums] i
  INNER JOIN [production_finance].[dbo].[hr_pe_mstr] p
    ON ( i.[SSN] = p.[hr_pe_ssn] )
WHERE
  ( p.[term_dt] IS NOT NULL )
  AND NOT EXISTS ( 
                   SELECT
                    *
                   FROM
                    [production_finance].[dbo].[hr_pe_mstr] p2
                   WHERE
                    p.[hr_pe_id] LIKE p2.[hr_pe_id] + '_'
                    AND p2.[term_dt] IS NOT NULL 
                 )

This syntax will identify employees with at least one non-terminated position:

select case when ISNUMERIC(hr_pe_id) = 1 
    then hr_pe_id
    else left(hr_pe_id, 5) end as EmployeeIDTrimmed
, max(case when Term_Dt is null then 'Y' else 'N' end) as StillEmployed
from MyTable
group by case when ISNUMERIC(hr_pe_id) = 1 
    then hr_pe_id
    else left(hr_pe_id, 5) end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM