Попробуйте следующий запрос и дайте мне знать, если вы получаете какие-либо ошибки.
Вы должны сохранить скобки специально для условия OR
.
Схема:
таблица user_info.
CREATE TABLE public.user_info(
user_id integer NOT NULL,
email_id character varying(255),
user_name character varying(255),
lob_id integer NOT NULL,
status_id integer,
CONSTRAINT user_info_pkey PRIMARY KEY (user_id)
)
WITH (
OIDS=FALSE
);
INSERT INTO user_info VALUES(111,'abc','abc@gmail.com' ,5,2);
INSERT INTO user_info VALUES(222,'def','def@gmail.com' ,5,6);
INSERT INTO user_info VALUES(333,'ghi','ghi@gmail.com' ,5,2);
INSERT INTO user_info VALUES(444,'jkl','jkl@hotmail.com',5,2);
таблица user_skill:
CREATE TABLE public.user_skill
(
user_id integer NOT NULL,
skill_id integer NOT NULL
)
WITH (
OIDS=FALSE
);
INSERT INTO user_skill VALUES(111,156);
INSERT INTO user_skill VALUES(222,156);
INSERT INTO user_skill VALUES(333,156);
INSERT INTO user_skill VALUES(444,156);
таблица assignment_details:
CREATE TABLE public.assignment_details
(
user_id integer NOT NULL,
role_id integer NOT NULL,
lob_id integer NOT NULL,
assignment_status character varying,
assignment_limited_threshold integer,
CONSTRAINT lsa_assignment_details_pkey PRIMARY KEY (user_id,
role_id, lob_id )
)
WITH (
OIDS=FALSE
);
INSERT INTO assignment_details VALUES(111,11,5,'Open',NULL);
INSERT INTO assignment_details VALUES(222,11,5,'No',NULL );
INSERT INTO assignment_details VALUES(333,11,5,'Limited',2);
INSERT INTO assignment_details VALUES(444,12,5,'Limited',10);
таблица loan_mapping:
CREATE TABLE public.loan_mapping
(
loan_number bigint NOT NULL,
spoc_id integer NOT NULL,
loan_spoc_map_id integer NOT NULL,
lob_id integer,
app_name VARCHAR(20),
CONSTRAINT loan_spoc_mapping_pk PRIMARY KEY (loan_spoc_map_id)
)
WITH (
OIDS=FALSE
);
INSERT INTO loan_mapping VALUES(222333,111,23,5,'SS');
INSERT INTO loan_mapping VALUES(222444,333,24,5,'SS');
INSERT INTO loan_mapping VALUES(222555,333,25,5,'SS');
INSERT INTO loan_mapping VALUES(333452,444,26,5,'SS');
INSERT INTO loan_mapping VALUES(777445,444,27,5,'SS');
SQL-запрос:
select ui.user_id from user_info ui
inner join user_skill lus on lus.skill_id = 156 and lus.user_id =
ui.user_id
left join
(select spoc_id,count(loan_number) loancount
from loan_mapping l where lob_id=5 and
app_name ='SS'
group by spoc_id)uc on uc.spoc_id = ui.user_id
inner join assignment_details ad on
ui.lob_id=ad.lob_id and ui.user_id=ad.user_id and
ui.lob_id=5 and ui.status_id=2 where ad.lob_id=5 and
ad.role_id=11 and (ad.assignment_status='Open' OR
(ad.assignment_status='Limited'
and ad.assignment_limited_threshold > uc.loancount))
И проверьте выходное значение в Ссылка SQL Fiddle
Возвращает следующие значениятолько.
Output
111
444