I have one table where I need all rows that meet the criteria in the first query (MIS), but only need to include 'EMP' if EMPID <92. I'm sure it's a simple statement, but I can't figure it out. Help!
SELECT MIS.*
FROM
(SELECT EMPID, ORG, LAST_NAME, FIRST_NAME, JCODE, DPTID, TITLE, STATUS, BU, LOC, CO, SUP_ID, AL_EMPID
FROM EMPLOYEE_TBL
WHERE REHIRE_ELIG <> 'Y'
AND HIRE_OVR <> 'Y'
AND SUP_ID IS NOT NULL
AND JCODE IS NOT NULL
AND ORG IN ('EMP','CWD')) MIS
WHERE MIS.ORG = 'EMP'
AND EMPID < '9200000'
ORDER BY MIS.ORG DESC, MIS.JCODE ASC
Sounds like a left outer join.
Something like:
select *
from table1 mis left outer join table1 msi2
on mis.id=mis2.id
where mis2.empid<92
Then anything in in mis2 is an id<92.
Just use an OR
in the WHERE
. My setup was done in SQL 2017, but that is fairly standard syntax and should work in any flavor of SQL.
MS SQL Server 2017 Schema Setup :
CREATE TABLE employee_tbl (
EMPID int
, ORG varchar(5)
, other_stuff varchar(50)
);
INSERT INTO employee_tbl (EMPID, ORG, other_stuff)
VALUES
( 90000000, 'EMP', 'IncludeMe' )
, ( 91000000, 'EMP', 'IncludeMe' )
, ( 91000001, 'CWD', 'IncludeMe' )
, ( 91000002, 'EMP', 'IncludeMe' )
, ( 92000000, 'EMP', 'ExcludeMe' )
, ( 95000000, 'EMP', 'ExcludeMe' )
;
Main Query :
SELECT *
FROM employee_tbl
WHERE ( ORG = 'EMP' AND EMPID < 92000000 )
OR ( ORG = 'CWD' )
Results :
| EMPID | ORG | other_stuff |
|----------|-----|-------------|
| 90000000 | EMP | IncludeMe |
| 91000000 | EMP | IncludeMe |
| 91000001 | CWD | IncludeMe |
| 91000002 | EMP | IncludeMe |
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.