title: Complex SQL query with group by and having
body: <p>I am having a table orders</p>
  
  <pre><code>orders (
  id  int unsigned not null,
  fcr_date  TIMESTAMP,
  completion_date TIMESTAMP,
  factory_no  varchar(255),
  vendor_no  varchar(255))
  </code></pre>
  
  <p>Please ignore the data type typos if any.</p>
  
  <p>I want to write a sql query that helps me filter the data per vendor factory. The data to fetch includes the number of orders per vendor factory(a unique group of vendor_no, factory_no), vendor_no, factory_no and the percentage of orders for which fcr_date is greater than completion_date(so percentage = number  of orders  where fcr_date is greater than completion date / count of orders). After  that  i  need  to  filter the data where percentage is greater than say 20%. </p>
  
  <p>I  wrote  the following  query:</p>
  
  <pre><code>SELECT  vendor_no As vendor,
          factory_no As factory,
          COUNT(1) as count,
          SUM(CASE WHEN fcr_date &gt; completion_date THEN 1 ELSE 0 END) as filter_orders,
      ROUND(filter_orders / count * 100, 4) as  percent  
  FROM    @orders
  GROUP BY vendor_no,
          factory_no
  HAVING percent&gt;20
  </code></pre>
  
  <p>but postgresql complains that  it needs  to  have a column  called percent in table to filter  the  results based on that. Any help is appreciated.</p>
  
  <p>Thanks.</p>