SQL时间问题,如何才能查到上月成本

来源:百度知道 编辑:UC知道 时间:2024/05/27 23:36:04
我要在SQL查询一张表里面的关于月份
cost成本表字段和一些数据如下
name price(成本) datetimes(日期)
餐饮收入 2000.00 2009-5-13 8:44:10 --表数据
商品零售 1500.00 2009-6-13 8:44:10

我要往虚拟表插入数据#costs 为虚拟表名
insert into #costs ([id],[name],[price](上月成本),[prices](本月成本))
我要怎样才能查出5月份和6月份的数据拼在一起啊?
就是这句的(5月成本)怎样才能得到,
select (5月的成本) ,price(本月的) from cost where datetimes='2009-6-13 8:44:10'

另外我这where 后面的时间是要改为参数来传入时间的,这个where后面的时间不能直接查出数据要转换,我转换不来,麻烦那位高手帮我弄下,急用!谢谢
哦,我那cost里面的一条数据就相当于一个月的成本,所有不用再SUM加了,我要的是查出来的上月成本和本月成本在一条数据里面然后插入虚拟表中

不知道你的id是干什么用的,如果有两条记录:
餐饮收入 2000.00 2009-5-13 8:44:10
餐饮收入 2000.00 2009-6-13 8:44:10
你的id显示多少?

所以我认为是你的误写,使用下面的sql建立一个视图就可以达到你的目的,请注意,我写的sql中sum函数不是为了求和用的,而是为了使group by好用才写的,对结果没有影响因为 sum(1000) 一个值 和 1000是相等的。

create view costs_view as
select name,
isnull(sum(case when datediff(m,datetimes,getdate())=1 then price end),0) 上月月成本,
isnull(sum(case when datediff(m,datetimes,getdate())=0 then price end),0) 本月成本
from cost
group by name

建好之后,select * from costs_view;就能查询出按name区分的本月和上个月的成本了。

---
以上,希望对你有所帮助。

获取月份用month() 转换类型用convert(),看不明白楼主的描述。

难,放到程序中处理吧

select sum(price) from cost where datetimes between &1 and &2 into cursor #costs;
&1和&2 是参数,&1="xxxx-xx-xx x:xx:xx"如果中间要加月份可以这样:
"xxxx-"+字符串+"-xx x:xx:xx"