我尝试了许多没有财富的解决方案。有人请帮忙
TABLE_1 :
car_type date_purchased down_payment
-------------------------------------
toyota 2/2012 $100
honda 4/2012 $500
ford 5/2012 $235
toyota 1/2013 $400
honda 4/2013 $20
Final_table (应该是这样的):
car_type date final_cost
--------------------------------
toyota 3/2012 $100
honda 4/2012 $500
ford 12/2012 $235
最终表应该像这样创建:
update final_table
set final_cost = table_1.down_payment
where final_table.car_type = table1.car_type
and max(table_1.date_purchased) <= final_table.date
费用应该是max(date_purchased)
小于或等于final_table.date
的费用
但是SQL Server不喜欢max和&lt; = part。
它一直在说要添加和分组,但他们没有工作
有谁知道如何让代码工作?
格拉西亚斯
答案 0 :(得分:0)
试试这个:
update final_table
set final_cost = table_1.down_payment
where final_table.car_type = table1.car_type
and final_table.date > (
select max(date_purchased) from table_1)
答案 1 :(得分:0)
我建议:
update ft
set final_cost = t1.down_payment
from final_table ft outer apply
(select top 1 t1.*
from table_1 t1
where t1.car_type = ft.car_type and
t1.date_purchased <= ft.date
order by t1.date_purchased desc
) t1;
答案 2 :(得分:0)
你不能在哪里使用聚合函数!使用group by with。
update final_table
set final_cost = table_1.down_payment
where final_table.car_type = table1.car_type
and table_1.date_purchased in (select table_1.date_purchased from table_1
group by table_1.date_purchased
having (max(table_1.date_purchased) <= final_table.date)
)