Sql 采用日期范围的问题

Sql 采用日期范围的问题,sql,sql-server,tsql,Sql,Sql Server,Tsql,我试图通过将w.adate1和w.adate2之间的日期范围取为m1.tdate,从m1中取m1.Price之和。问题在于m1。价格计算不正确。请检查SQL代码 with m1 as ( select sum(c.price) as Price,c.tdate ,c.unit from Dim_stocks c group by c.tdate ,c.unit ) select sum(w.total) as cost, w.a_time, w

我试图通过将w.adate1和w.adate2之间的日期范围取为
m1.tdate,从m1中取
m1.Price
之和。问题在于
m1。价格计算不正确。请检查SQL代码

with m1 as 
(
    select sum(c.price) as Price,c.tdate ,c.unit
    from Dim_stocks c 
    group by c.tdate ,c.unit
)
select
    sum(w.total) as cost,
    w.a_time,
    w.unit,
    sum(m1.Price) as price
from Target_Shipment w 
left join m1 on m1.tdate = w.a_time and m1.unit = w.unit
where m1.tdate between cast(DATEADD(month,DATEDIFF(month,0,w.a_time),0) as date) and w.a_time    
group by w.a_time, w.unit

尽管在不正确了解问题的情况下无法回答。需要样本数据。但是,您是否只想按日期获取总和(价格)组

with m1 as 
(
    select
        sum(c.price) over (partition by cast(c.tdate-DAY(c.tdate)+1 as date) order by tdate rows between unbounded preceding and current row) as Price
        , c.tdate, c.unit
    from Dim_stocks c 
)
select
    sum(w.total) as cost,
    w.a_time,
    w.unit,
    sum(m1.Price) as price
from Target_Shipment w 
left join m1 on m1.tdate = w.a_time and m1.unit = w.unit
where m1.tdate between cast(DATEADD(month,DATEDIFF(month,0,w.a_time),0) as date) and w.a_time    
group by w.a_time, w.unit
例如:

create table Dim_stocks(unit varchar(10), tdate date, price float);
insert into Dim_stocks values('MUM' ,'3/1/2021',    2010.3);
insert into Dim_stocks values('MUM' ,'3/1/2021',    4308.49);
insert into Dim_stocks values('MUM' ,'3/2/2021',    2690.75);
insert into Dim_stocks values('MUM' ,'3/5/2021',    3091.4);
insert into Dim_stocks values('COL' ,'2/10/2020',   4025.99);
insert into Dim_stocks values('COL' ,'2/28/2021',   4032.73);
insert into Dim_stocks values('COL' ,'2/1/2021',    3978.79);
insert into Dim_stocks values('COL' ,'11/23/2020',  4157.69);
insert into Dim_stocks values('PUN' ,'11/3/2020',   4032.13);
insert into Dim_stocks values('COL' ,'11/3/2020',   4025.99);
insert into Dim_stocks values('PUN' ,'11/1/2020',   4019.24);

select
    sum(c.price) over (partition by DATEADD(day, 1, EOMONTH(DATEADD(month, -1, c.tdate))) order by tdate rows between unbounded preceding and current row) as Price
    , c.tdate, c.unit
from Dim_stocks c 
     
输出:

价格 日期 单元 4025.99 2020-02-10 上校 4019.24 2020-11-01 双关语 8051.37 2020-11-03 双关语 12077.36 2020-11-03 上校 16235.05 2020-11-23 上校 3978.79 2021-02-01 上校 8011.52 2021-02-28 上校 2010.3 2021-03-01 妈妈 6318.79 2021-03-01 妈妈 9009.54 2021-03-02 妈妈 12100.94 2021-03-05 妈妈
向我们展示一些样本表数据和预期结果-全部为格式化文本(不是图像)。请分享一些样本代码“问题在于m1。价格计算不正确。”-您需要通过向我们展示样本数据、预期结果和实际结果来澄清这意味着什么。您好,感谢您的回复。您将源数据显示为一个表,但您的查询引用了两个表。我们已经提到了数据。。请检查并提出建议。谢谢我是按时间和单位分组的。但tdate需要通过“从每月第一天(tdate)到tdate”进行分组。示例:如果tdate为2020年3月17日,则价格应为“日期1stMarch20至17thMarch20的总和(价格)”明白了。我已经修改了我的答案。请检查。非常感谢您的输入,但在m1组中,by是在每月第一天(tdate)完成的,我们需要获取从每月第一天到tdate的范围。对这个pls有什么意见吗?