Search code examples
sql-serverloopst-sqldynamic-variables

using all values from one column in another query


I am trying to find a solution for the following issue that I have in sql-server:

I have one table t1 of which I want to use each date for each agency and loop it through the query to find out the avg_rate. Here is my table t1:

Table T1:

+--------+-------------+
| agency |  end_date   |
+--------+-------------+
|      1 | 2017-10-01  |
|      2 | 2018-01-01  |
|      3 | 2018-05-01  |
|      4 | 2012-01-01  |
|      5 | 2018-04-01  |
|      6 | 2017-12-01l |
+--------+-------------+

I literally want to use all values in the column end_date and plug it into the query here (I marked it with ** **):

    with averages as (
select      a.id as agency
            ,c.rate  
            , avg(c.rate) over (partition by a.id  order by a.id )  as avg_cost


from table_a as a
                     join  rates c on a.rate_id = c.id


and c.end_date =  **here I use all values from t1.end_date** 
and c.Start_date =  **here I use all values from above minus half a year** = dateadd(month,-6,end_date)

group by    a.id 
            ,c.rate  
            )
select distinct agency, avg_cost  from averages 
order by 1 

The reason why I need two dynamic dates is that the avg_rates vary if you change the timeframe between these dates.

My problem and my question is now:

How can you take the end_date from table t1 plug it into the query where c.end_date is and loop if through all values in t1.end_date?

I appreciate your help!


Solution

  • I can think of several ways to do this - Cursor, StoredProcedure, Joins ... Given the simplicity of your query, a cartesian product (Cross Join) of Table T1 against the averages CTE should do the magic.