*
from
shipmentlist,shipmentscrib
where
(shipmentlist.shipmentlistno=shipmentscrib.shipmentlistno)
and (year(shipmentlist.shipmentdate)=year(now()))
and (month(shipmentlist.shipmentdate)=month(now())
or month(shipmentlist.shipmentdate)=month(now())-1 )
ORDER BY shipmentdate DESC
格式化了一下你的SQL,分析一下。
假如今天是 2012年1月1日。
那么上面的条件。
将变为
year = 2012 and month = 1 OR month = 0
其实,对于 查询 当月和上一月
相当于
shipmentlist.shipmentdate >= 上月的1号
AND shipmentlist.shipmentdate <下月的1号
LAST_DAY(NOW()) 可以获取 本月的最后一天.
DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) 可以获取下月第一天。
DATE_SUB ( DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) INTERVAL 2 MONTH ) 可以获取上月的1号
(也就是用 下月的1号 减少2个月,从而获取 上月的1号)
最后 SQL 修改为:
select
*
from
shipmentlist,shipmentscrib
where
(shipmentlist.shipmentlistno=shipmentscrib.shipmentlistno)
and shipmentlist.shipmentdate >= DATE_SUB ( DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) INTERVAL 2 MONTH )
AND shipmentlist.shipmentdate <DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY )
ORDER BY shipmentdate DESC
----表名tb,日期字段dt,金额字段,amtselect sum(last_mon_amt) last_mon_amt,sum(cur_mon_amt) cur_mon_amt,sum(last_day_amt ) last_day_amt from(
select sum(amt) last_mon_amt,0 cur_mon_amt,0 last_day_amt from tb where date_format(dt, '%Y%m') = date_format(date_add(sysdate(), interval -1 month), '%Y%m') --上月合计
union all
select 0 last_mon_amt,sum(amt) cur_mon_amt,0 last_day_amt from tb where date_format(dt, '%Y%m') = date_format(sysdate(),'%Y%m') --当月合计
union all
select 0 last_mon_amt,0 cur_mon_amt,sum(amt) last_day_amt from tb where date_format(dt, '%Y%m%d') = date_format(date_add(sysdate(), interval -1 day),'%Y%m%d') --昨日合计
) tb1
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)