title: SELECT count of subquery before applying LIMIT (clickhouse)
body: <p>I have a subquery that aggregates some UNION ALL selects. Over that I prepare the <code>SELECT</code> to create cross-tab and limit it to let's say 20. I would like to be able to retrieve the total COUNT of sub query results before I am limiting them in main query. This is for the purpose of trying to build a pagination that receives the total number of records and then the specific page record grid.</p>
  
  <p>Sample query:</p>
  
  <pre><code>SELECT 
      name, 
      sumIf(metric_value, metric_name = 'data') AS data,
      sumif(....
  FROM
      (SELECT 
           name, metric_name, SUM(metric_value) as metric_value 
       FROM
           (SELECT 
                name, 'data' AS metric_name, SUM(data) AS metric_value 
            FROM 
                table 
            WHERE 
                date &gt; '2017-01-01 00:00:00' 
            GROUP BY 
                name
  
            UNION ALL
  
            SELECT 
                name, 'data' AS metric_name, SUM(data) AS metric_value 
            FROM 
                table2 
            WHERE 
                date &gt; '2017-01-01 00:00:00' 
            GROUP BY 
                name
  
            UNION ALL
  
            SELECT 
                name, 'data' AS metric_name, SUM(data) AS metric_value 
            FROM 
                table3 
            WHERE 
                date &gt; '2017-01-01 00:00:00' 
            GROUP BY 
                name
  
            UNION ALL
  
            .
            .
            .)
      GROUP BY 
          name, metric_name)
  GROUP BY 
      name 
  ORDER BY 
      name ASC
  LIMIT 0,20;
  </code></pre>
  
  <p>The first subselect returns tons of data, so I thought I can count it and return as one column value, or row and it would propagate to main select that limits 20 results. Because I need to know the entire set of results but don;t want to call the same query twice without limit and with limit just to get COUNT. There are at least 12 UNION ALL third level sub selects, so why waste resources. I am looking to try generic SQL solutions not necessarily related to ClickHouse</p>
  
  <p>I was thinking of using <code>count(*) OVER ()</code>, however that is not supported, so if thats only option I know I need to run query twice.</p>