Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming your table is named Contacts:</p> <pre><code>SELECT RecordId, C1.PersonId, 'Initial Record' AS RecordStatus FROM Contacts C1 INNER JOIN (SELECT PersonId, COUNT(PersonId) as PersonCount FROM Contacts GROUP BY PersonId) C2 ON C1.PersonId = C2.PersonId WHERE SentDate IS NULL AND PersonCount = 1 UNION SELECT RecordId, C1.PersonId, 'Follow Up Record' AS RecordStatus FROM Contacts C1 INNER JOIN (SELECT PersonId, COUNT(PersonId) as PersonCount FROM Contacts GROUP BY PersonId) C2 ON C1.PersonId = C2.PersonId WHERE SentDate IS NULL AND PersonCount &gt; 1 ORDER BY RecordId </code></pre> <p>The query works by assuming that if a PersonId only exists once in the table, it's an initial record; otherwise, it is a Follow Up Record.</p> <p><strong>EDIT</strong></p> <p>By popular demand, now with 100% less UNION!</p> <pre><code>SELECT RecordId, C1.PersonId, CASE WHEN PersonCount &gt; 1 THEN 'Follow Up Record' WHEN PersonCount = 1 THEN 'Initial Record' END AS RecordStatus FROM Contacts C1 INNER JOIN (SELECT PersonId, COUNT(PersonId) as PersonCount FROM Contacts GROUP BY PersonId) C2 ON C1.PersonId = C2.PersonId WHERE SentDate IS NULL </code></pre> <p><strong>EDIT 2</strong></p> <p>It's probably overkill, but here's my first shot at a CTE version:</p> <pre><code>With PersonCountCTE (PersonId, PersonCount) AS ( SELECT PersonId, COUNT(PersonId) AS PersonCount FROM Contacts GROUP BY PersonId ) SELECT RecordId, C1.PersonId, CASE WHEN PersonCount &gt; 1 THEN 'Follow Up Record' WHEN PersonCount = 1 THEN 'Initial Record' END AS RecordStatus FROM Contacts C1 INNER JOIN PersonCountCTE C2 ON C1.PersonId = C2.PersonId WHERE SentDate IS NULL </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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