Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL group by clause understanding (simple question / SQL server 2005)
    primarykey
    data
    text
    <p>HI all, I'm having some difficulty understanding the rationale behind group by aggregation in sql server 2005.</p> <p>I have the following query which works fine and returns one row for each contact.id and the 1st occurence of event</p> <pre><code>SELECT contact.id ,MIN(eve.date_created) FROM _contact contact WITH(nolock) INNER JOIN table2 tb2 WITH (nolock) ON contact.id = tb2.id1 INNER JOIN _event eve WITH (nolock) ON tb2.id2 = eve.id INNER JOIN _cashtable cash WITH (nolock) ON cash.contact_id = contact.id GROUP BY contact.id </code></pre> <p>However what I'm looking for is to have the following query and still only pull out one row per contact.id</p> <pre><code>SELECT contact.id ,MIN(eve.date_created) ,cash.id2 -- the cash linked to the first event ,eve.id -- the first event linked to the contact FROM _contact contact with (nolock) INNER JOIN _table2 tb2 WITH (nolock) ON contact.id = tb2.id1 INNER JOIN _event eve WITH (nolock) ON tb2.id2 = eve.id INNER JOIN _cashtable cash WITH (nolock) ON cash.contact_id = contact.id GROUP BY contact.id </code></pre> <p>I get the standard error message saying that I need to add in cash.id2 and eve.id into the group by clause, which returns results I don't want.</p> <p>I know that there are the potential options of using rank() / partitioning or even including the </p> <pre><code>select(MIN(eve.date_created) </code></pre> <p>in the FROM clause, but I am not sure which would be best to put this and am still quite confused as to why SQL requires everything to be included in the group by statement and so any advice would be great :)</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    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.
    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