title: Does Snowflake create a Temp Table for CTEs?
body: <p>I am analyzing some stock data using the following query to average the closing price on monthly basis:</p>
  <pre><code>// use ZEPL_STOCKS;
  with MONTHLY_AVERAGES AS
  (SELECT DISTINCT
    SYMBOL
    , YEAR(DATE) as YEAR
    , month(DATE) as MONTH
    , avg(close) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_CLOSE_AVG 
    , avg(adjclose) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_ADJCLOSE_AVG 
    , avg(open) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_OPEN_AVG 
    , avg(high) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_HIGH_AVG
    , avg(low) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_LOW_AVG 
    , avg(volume) over(partition by symbol, year(DATE), month(DATE)) as MONTHLY_VOLUME_AVG 
   
  from 
  STOCK_HISTORY)
  select 
    M_AVG_2020.SYMBOL
    , M_AVG_2020.MONTH
    , M_AVG_2020.MONTHLY_CLOSE_AVG CLOSE_AVG_2020 
    , M_AVG_2021.MONTHLY_CLOSE_AVG CLOSE_AVG_2021
    , M_AVG_2022.MONTHLY_CLOSE_AVG CLOSE_AVG_2022
    FROM MONTHLY_AVERAGES as M_AVG_2020
  inner join MONTHLY_AVERAGES as M_AVG_2021
    on M_AVG_2020.SYMBOL=M_AVG_2021.SYMBOL AND M_AVG_2020.MONTH=M_AVG_2021.MONTH
  inner join MONTHLY_AVERAGES as M_AVG_2022
    on M_AVG_2020.SYMBOL=M_AVG_2022.SYMBOL AND M_AVG_2020.MONTH=M_AVG_2022.MONTH
  where M_AVG_2020.YEAR=2020 and M_AVG_2021.YEAR=2021 and M_AVG_2022.YEAR=2022 --and M_AVG_2020.SYMBOL='ORCL'
  ORDER BY SYMBOL, MONTH;
  </code></pre>
  <p>While this query works, it is very slow when more years are analyzed or a finer time grain is used. What is the best way to optimize this query?</p>
  <p>here is the query plan:
  <a href="https://i.stack.imgur.com/EKzuY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKzuY.png" alt="enter image description here" /></a></p>