title: Grouping from a CTE which is within a CTE
body: <p>I have a CTE like so - </p>
  
  <pre><code>with cte (
      org1, org2, org3
      , ind1, ind2, ind3
    ) as (
      -- a bunch of queries
      ) 
    SELECT 
      org1 as org, 
      ind2 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org1, 
      ind2 
    union all 
    SELECT 
      org1 as org, 
      ind3 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org1, 
      ind3 
    union all 
    SELECT 
      org2 as org, 
      ind1 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org2, 
      ind1 
    union all 
    SELECT 
      org2 as org, 
      ind3 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org2, 
      ind3 
    union all 
    SELECT 
      org3 as org, 
      ind1 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org3, 
      ind1 
    union all 
    SELECT 
      org3 as org, 
      ind2 as ind, 
      count(*) as count_final 
    from 
      cte 
    group by 
      org3, 
      ind2;
  </code></pre>
  
  <p>Once I have org, ind and count_final, how do I do this - </p>
  
  <pre><code>select org, ind, sum(count_final) as count from cte_final
  group by org, ind
  </code></pre>
  
  <p>I tried to create another cte on top of this one so I could run this query but I am getting an error stating that there is an ambiguous reference to <code>org</code>. This is what I have tried - </p>
  
  <pre><code>with cte_final (org, ind)
  as (
  with cte (org1, org2, org3, ind1, ind2, ind3)
  as (
  
  --a bunch of queries
  
      )
  
  SELECT org1 as org , ind2 as ind, count(*) as count_final from cte
  group by org1 , ind2 
  union all
  SELECT org1 as org , ind3 as ind, count(*) as count_final from cte
  group by org1 , ind3 
  union all
  SELECT org2 as org , ind1 as ind, count(*) as count_final from cte
  group by org2 , ind1
  union all
  SELECT org2 as org , ind3 as ind, count(*) as count_final from cte
  group by org2 , ind3
  union all
  SELECT org3 as org , ind1 as ind, count(*) as count_final from cte
  group by org3 , ind1
  union all
  SELECT org3 as org , ind2 as ind, count(*) as count_final from cte
  group by org3 , ind2
  ;
  )
  select org, ind, sum(count_final) as count from cte_final
  group by org, ind;
  </code></pre>
  
  <p>Input - </p>
  
  <pre><code>Org             Ind             Count_Final
  "1023043221"    "156832423986"  "17"
  "1023043221"    "156832423986"  "1"
  "14325495102"   "142722349564"  "1"
  </code></pre>
  
  <p>I want this result - </p>
  
  <pre><code>Org             Ind             Count_Final
  "1023043221"    "156832423986"  "18"
  "14325495102"   "142722349564"  "1"
  </code></pre>