Z
Z
Zunga2019-11-05 11:36:56
PostgreSQL
Zunga, 2019-11-05 11:36:56

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

It works fine and returns what you need, i.e. a list of clients for whom more than 60 days have passed since the last task was closed.
However, if you write the following construction:
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
  )

Then the query starts returning a small number of companies for which less than 60 days have passed since the last task was closed. I honestly don't understand why this is happening.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2019-11-05
SQL

it would be necessary to somehow link the tables in select and in exists. otherwise this same exists will be performed for all records

M
Melkij, 2019-11-05
@melkij

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 question

Ask a Question

731 491 924 answers to any question