title: How to select all distinct values from column A which have certain value in column B in mySQL
body: <p>Introduction to the problem:
  I am working on barcode tracking system which has 5 scanning stations placed along the production line starting from StationID 1 and the final station is StationID 5. Each barcode corresponds to an item that is being manufactured along the line. Some items, like the one with Barcode 95821 don't go through preprocessing and therefore are not scanned by StationID 1. </p>
  
  <p>The problem: 
  I am having hard time building a query that shows all barcodes that have passed StationID 2 but haven't reached StationID 3, or 4 or 5: 
  List all barcodes that:
   - have passed both StationID 1 and StationID 2 (like 95813,95814,95823, 95824)
   - have passed StationID 2 only (like 95821) since it doesn't go through preprocessing</p>
  
  <p>Here is an example table called scanstations:</p>
  
  <pre><code>+---------+-----------+----------+
  | Barcode | StationID |   Time   |
  +---------+-----------+----------+
  |   95813 |         1 | 11:30:01 |
  |   95814 |         1 | 11:30:05 |
  |   95823 |         1 | 11:30:10 |
  |   95824 |         1 | 11:30:20 |
  |   95821 |         2 | 11:35:10 |
  |   95813 |         2 | 11:40:01 |
  |   95814 |         2 | 11:40:02 |
  |   95823 |         2 | 11:30:10 |
  |   95824 |         2 | 11:30:20 |
  |   95813 |         3 | 11:40:01 |
  |   95814 |         3 | 11:40:02 |
  |   95813 |         4 | 11:45:10 |
  |   95814 |         4 | 11:45:30 |
  |   95813 |         5 | 11:47:20 |
  +---------+-----------+----------+
  </code></pre>
  
  <p>The expected result set:</p>
  
  <pre><code>+---------+
  | Barcode |
  +---------+
  |   95821 |
  |   95823 |
  |   95824 |
  +---------+
  </code></pre>
  
  <p>I use the following query to list all barcodes that have been scanned by StationID 1 and haven't been scanned by any other station.</p>
  
  <pre><code>SELECT 
      Barcode
  FROM
      scanstations s
  GROUP BY Barcode
  HAVING SUM(CASE
      WHEN s.StationID = 1 THEN 0
      ELSE 1
  END) = 0
  </code></pre>