如何使用按条件分组加入不同的表

时间:2021-04-06 05:10:37

标签: sql sql-server tsql

我有两个不同的临时表。

这是一个例子:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=7d0539e15be76f61cd3219c1087e524f

您可以在运行代码时查看示例表。

这是我的连接表代码。

select cat01
    , cat02
    , avg(price) as prc
from temp01
where 1=1
and dt_day between '2019-01-01' and '2019-01-05'
group by cat01, cat02

但是,我不知道加入 temp01(cat01, cat02, dt_day) 和 temp02(cat01, cat02, start_dt, end_dt) 。

我的观点是通过结合 temp01 和 temp02 创建一个结果表。

请检查我的代码。

3 个答案:

答案 0 :(得分:1)

这是您需要的结果吗?

select t1.cat01, t1.cat02, t2.start_dt, t2.end_dt, avg(isnull(t1.price,0)) avg_price from temp01 t1, temp02 t2 group by t1.cat01, t1.cat02, t2.start_dt, t2.end_dt

答案 1 :(得分:1)

不是 100% 的请求是什么,但使用它可能会成功。

select *
from 
    (select cat01
        , cat02
        , avg(price) as prc
    from temp01
    where 1=1
    and dt_day between '2019-01-01' and '2019-01-05'
    group by cat01, cat02)
inner join
    (select *
    from temp02)
on
    temp01.cat01 = temp02.cat01
and
    temp01.cat02 = temp02.cat02
    

答案 2 :(得分:1)

我认为您只需要将 NULL 设为零并取平均值,因为 avg 忽略 NULL 值,而且您的结果表明也应该使用 cat01 字段连接表。

enter image description here

select t1.cat01, t1.cat02, start_dt, end_dt, cast(avg(isnull(price, 0)) as numeric(18,2)) price
from temp01 t1
join temp02 t2 on t1.cat01 = t2.cat01 and t1.dt_day between '2019-01-01' and '2019-01-05'   --t2.start_dt and t2.end_dt
group by t1.cat01, t1.cat02, start_dt, end_dt
order by t1.cat01 desc, t1.cat02

请参阅数据库<>小提琴 here

相关问题