title: Create a stored procedure such that rows with same key are converted into a column
body: <p>You are given the table tracks, which contains the following columns:</p>
  
  <ol>
  <li><code>received_at</code>: the unique timestamp of the action </li>
  <li><code>event_name</code>: the name of the action that was performed at this time </li>
  <li><code>anonymous_id</code>: the anonymous ID of a user </li>
  <li><code>user_id</code>: the user ID, which can be null</li>
  </ol>
  
  <p>This is the mentioned DDL for the problem.</p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS `tracks` 
  (
      `received_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
      `event_name` varchar(300) NOT NULL,
      `anonymous_id` int(2) NOT NULL,
      `user_id` int(2)
  ) DEFAULT CHARSET=utf8;
  
  INSERT INTO `tracks` (`received_at`, `event_name`, `anonymous_id`,`user_id`) 
  VALUES
    ('2016-01-01 12:13:12', 'buttonClicked', 1,NULL),
    ('2016-01-02 12:14:15', 'pageReloaded', 3,NULL),
    ('2016-02-02 13:15:13', 'pageRendered', 2,NULL),
    ('2016-02-03 13:15:23', 'commentWritten', 3,NULL),
    ('2016-03-03 14:15:15', 'avatarUpdated', 2,2),
    ('2016-03-04 14:15:24', 'statusUpdated', 1,1);
  </code></pre>
  
  <p>Task is to find two events for each <code>anonymous_id</code>, which will be the column <code>anonym_id</code> in the returned table. Find the last event where the user was tracked only by <code>anonymous_id</code> (column <code>last_null</code>) and the first event that was tracked by <code>user_id</code> (column <code>first_notnull</code>). The resulting table should be sorted by <code>anonym_id</code>.</p>
  
  <p>As mentioned according to the problem statement this is the desired outcome.</p>
  
  <pre><code>anonym_id | last_null     | first_notnull
  ----------+---------------+---------------
  1         | buttonClicked | statusUpdated
  2         | pageRendered  | avatarUpdated
  3         | commentWritten| NULL
  </code></pre>
  
  <p>We have tried achieving the outcome using UNION on two different query resultset as shown but still not able to get the desired outcome. </p>
  
  <pre><code>select a.anonymous_id,a.event_name,b.event_name from (
  (select anonymous_id,event_name from tracks where user_id is null group by anonymous_id) as a 
  union 
  (select anonymous_id,event_name from tracks where user_id is not null group by anonymous_id) as b  
  </code></pre>
  
  <p>Can Someone throw light on how to come to the desired outcome? How to get the outcome in the most efficient less time-consuming way? </p>