在另一个查询中使用一列中的所有值

using all values from one column in another query

我正在尝试为我在 sql-server 中遇到的以下问题找到解决方案:

我有一个 table t1,我想为每个机构使用每个日期,并通过查询循环它以找出 avg_rate .这是我的 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 |
+--------+-------------+

我真的想使用列 end_date 中的所有值并将其插入此处的查询(我用 ** ** 标记):

    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 

我需要两个动态日期的原因是,如果您更改这些日期之间的时间范围,avg_rates 会有所不同。

我的问题和我现在的问题是:

如何从 table t1 中获取 end_date 并将其插入到 c.end_date 所在的查询中,然后循环遍历 t1.end_date 中的所有值?

感谢您的帮助!

您真的需要加窗平均值吗?试试这个。

;with timeRanges AS
(
    SELECT
        T.end_date,
        start_date = dateadd(month,-6, T.end_date)
    FROM
        T1 AS T
)
select      
    a.id as agency,
    c.rate,
    T.end_date,
    T.start_date,
    avg_cost = avg(c.rate)
from 
    table_a as a
    join  rates c on a.rate_id = c.id
    join timeRanges AS T ON A.DateColumn BETWEEN T.start_date AND T.end_date
group by   
    a.id ,
    c.rate,
    T.end_date,
    T.start_date

您需要一个日期列来根据 T1 加入您的数据(在本例中我称之为 DateColumn),否则所有时间范围都会 return 相同的平均值。

我可以想到几种方法 - CursorStoredProcedureJoins ... 鉴于您查询的简单性,Table T1[=19= 的 笛卡尔积 (Cross Join) ] 针对 平均值 CTE 应该可以发挥作用。