Answer the question
In order to leave comments, you need to log in
Postgres - SQL query (EXIST) not working correctly?
All hello, I ask for help:
There are two tables sys_accounts (clients) and sys_activities (tasks for clients).
There is such a working request (In fact, its task is to return clients for whom more than 60 days have passed since the last task was closed):
SELECT DISTINCT ON (activ.account_guid) (SELECT name FROM sys_accounts WHERE guid=activ.account_guid),
(SELECT extract(day from now() - activ.datefinish) FROM sys_accounts WHERE guid=activ.account_guid), activ.datefinish FROM sys_activities activ
INNER JOIN sys_accounts account ON account.guid = activ.account_guid
WHERE activ.datefinish IS NOT NULL AND activ.dc_status_guid='df11a68c-20d3-46e2-840f-2e4548aacf1b'
AND extract(day from now() - activ.datefinish)>=60
AND (account.dc_stage_guid!='83e0d2dd-926e-4764-9d04-8996ce2d1178' AND account.dc_stage_guid!='fc8e8746-cc71-4d52-b6a4-9186e3da653b')
ORDER BY activ.account_guid,activ.datefinish DESC
SELECT name from sys_accounts account where
exists(
SELECT DISTINCT ON (activ.account_guid) activ.account_guid, activ.datefinish FROM sys_activities activ
INNER JOIN sys_accounts account ON account.guid = activ.account_guid
WHERE activ.datefinish IS NOT NULL AND activ.dc_status_guid='df11a68c-20d3-46e2-840f-2e4548aacf1b'
AND extract(day from now() - activ.datefinish)>=60
AND (account.dc_stage_guid!='83e0d2dd-926e-4764-9d04-8996ce2d1178' AND account.dc_stage_guid!='fc8e8746-cc71-4d52-b6a4-9186e3da653b')
ORDER BY activ.account_guid,activ.datefinish DESC
)
Answer the question
In order to leave comments, you need to log in
it would be necessary to somehow link the tables in select and in exists. otherwise this same exists will be performed for all records
Since the time of the topic on sql.ru, I don’t want to find out what it was that you built and why it’s so difficult.
It is a very bad idea to try to use the same identifiers many times. Either the whole query works for you according to the principle if exists subquery then take all the rows of the table else an empty set, or the conditions are somehow intertwined with each other in an unobvious way due to the coincidence of identifiers.
You can try using exists as a one-time filter in general - but there is usually an error on exists for an uncorrelated query.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question