title: TSQL distinct list, but with extra data if a single original item
body: <p><em>Ideally I'd like SQL2008 compliant answers, due to customer constraints</em></p>
  <p>I need a distinct list of items, but with a column that returns a specific piece of data <strong>if</strong> the original data only had a single item in the first place...</p>
  <p>Example data...</p>
  <pre><code>Id   Code
  1    A
  2    A
  3    B
  </code></pre>
  <p>In the above example data I want to return a distinct list of <code>Code</code>, but if only a single instance of that code exists I want the <code>Id</code> to be returned (otherwise <code>null</code>)</p>
  <p>Expected output...</p>
  <pre><code>Code  Id
  A     null
  B     3
  </code></pre>
  <p>I've got the following, but it feels like there should be an easier way of doing it, maybe using <code>GROUP BY</code>...</p>
  <pre><code>; WITH Data AS (
      SELECT Code, Id ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Id) AS RowNum
      FROM MyTable
  )
  SELECT D1.Code, CASE (SELECT COUNT(*) FROM Data D2 WHERE D2.Code = D1.Code) WHEN 1 THEN D1.Id ELSE NULL END
  FROM Data D1
  WHERE D1.RowNum = 1
  </code></pre>
  <p>Can this be done in a better way?</p>