Note that there are some explanatory texts on larger screens.

plurals
  1. POSelect users who did a purchase after a search where some conditions apply in PostgreSQL?
    primarykey
    data
    text
    <p>I have this case: users are making searches on the website and some of them purchase. How would you select users over 18 who did a <strong>search</strong> without a following <strong>purchase</strong> where purchase condition is true and search session = purchase session</p> <p>This selects users with search events and age over 18.</p> <pre><code>select DISTINCT ON (id) id, email, users.age, events.type, events.createdon from users LEFT JOIN events ON events.user = users.users where events.type='search' and age&gt;18 and events.condition is true </code></pre> <p>How would I add the condition that they did a <strong>search</strong> event previously in the same session?</p> <p>The table structure for events:</p> <pre><code>----------------------------------------------------- | user | event | date | condition | session | ------------------------------------------------------| | 1 | search | 08-10-2013 | true | A | | 1 | search | 08-10-2013 | true | A | | 2 | search | 08-10-2013 | false | B | | 2 | purchase | 09-10-2013 | false | A | | 2 | search | 09-10-2013 | true | C | | 1 | purchase | 09-10-2013 | true | A | | 3 | search | 09-10-2013 | false | D | | 2 | search | 10-10-2013 | true | H | | 4 | search | 10-10-2013 | false | E | | 4 | search | 10-10-2013 | false | E | | 3 | search | 11-10-2013 | true | D | | 2 | other | 11-10-2013 | true | H | | 1 | search | 11-10-2013 | true | F | | 1 | purchase | 12-10-2013 | true | F | | 3 | purchase | 12-10-2013 | false | D | | 4 | search | 12-10-2013 | true | G | | 2 | other | 12-10-2013 | true | A | ----------------------------------------------------- </code></pre> <p>and the user table is:</p> <pre><code>------------------------ | user | email | age | ------------------------ | 1 | a | 22 | | 2 | b | 34 | | 3 | c | 15 | | 4 | d | 44 | | 5 | e | 39 | ------------------------ </code></pre> <p>The result should be 2 and 4:</p> <pre><code>1 a -&gt; NO because did purchase with condition=true 2 b -&gt; YES because did search, did purchase BUT condition=false 3 c -&gt; NO because did search, did purchase with condition=false BUT age&lt;18 4 d -&gt; YES because did search and no purchase </code></pre> <p>Thank you, I'm just starting with Postgres from Mongo and is much better!</p> <p>UPDATE: corrected result for example</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload