title: Complex ORDER BY Statement
body: <p>I have this query:</p>
  
  <pre><code>SELECT itemID, item, note, sourceItemID, title, collectionName,
         count(tagID) as qtTag,
         count(modalityID) as qt_Modality, extra
         FROM items INNER JOIN factors ON items.itemID = factors.zotero_itemID
         WHERE (collectionID = :collectionID) AND (tagID = :tagID1 OR tagID = :tagID2) group by itemID, item, note, sourceItemID, title, collectionName, extra ORDER BY EXTRA;
  </code></pre>
  
  <p>Now, every ITEM is connected to one or many TAGID's. What I need is to order the result in a way that ITEMS linked to TagID1 and TagID2 comes first in order the others could be ordered by EXTRA field. 
  Is it possible to do that?
  I have tried with  ORDER BY CASE statement but I cannot make it work it out.</p>
  
  <p>this is a sample of the result:</p>
  
  <p><img src="https://i.stack.imgur.com/Lcmv5.png" alt="enter image description here"></p>
  
  <p>As you can see, the items are ordered by the EXTRA field. But I need to put ITEMS linked to TagID1 and TagID2 first, but these fields are not shown in the result. All I need is the order.</p>
  
  <p>I had tried this code, but doesn't work:</p>
  
  <pre><code>SELECT itemID, item, note, sourceItemID, title, collectionName,
         count(tagID) as qtTag,
         count(modalityID) as qt_Modality, extra
         FROM items INNER JOIN factors ON items.itemID = factors.zotero_itemID
         WHERE (collectionID = :collectionID) AND (tagID = :tagID1 OR tagID = :tagID2) group by itemID, item, note, sourceItemID, title, collectionName, extra ORDER BY CASE WHEN tagID1 = :TagID1 THEN 1 WHEN tagID2 = :tagID2 THEN 2 END,  EXTRA;
  </code></pre>
  
  <p>Obs. I'm using Firebird 3.0 database</p>