日期:2014-05-16  浏览次数:20618 次

一条sql中查询今年和去年同期
下面条sql查询出的是今年某一周的销售数据,怎么在同一条sql中查询出去年同期的数据呢?
select store,sum(endprice*nb) as sum_sales_lweek,SUM(nb) as sum_nb,count(distinct nos) as sum_nos
from [CMD].[dbo].[cmd_xjjx_sale]
where outdate<='20140223' and outdate>='20140216' and endprice>0
group by store

------解决方案--------------------
不知道是不是你说的意思
select a.store,sum_sales_lweek,sum_nb,sum_nos,[2013sum_sales_lweek],[2013sum_nb],[2013sum_nos] from 
(select store,sum(endprice*nb) as sum_sales_lweek,SUM(nb) as sum_nb,count(distinct nos) as sum_nos 
from [CMD].[dbo].[cmd_xjjx_sale] where outdate<='20140223' and outdate>='20140216' and endprice>0 
group by store) a,
(select store,sum(endprice*nb) as [2013sum_sales_lweek],SUM(nb) as [2013sum_nb],count(distinct nos) as [2013sum_nos]
from [CMD].[dbo].[cmd_xjjx_sale] where outdate<='20130223' and outdate>='20130216' and endprice>0 
group by store) b where a.store=b.store
------解决方案--------------------

declare @begindate varchar(20),@enddate varchar(20)
select @begindate='20140216',@enddate='20140223'

select a.store,
       a.sum_sales_lweek,a.sum_nb,a.sum_nos,
       isnull(b.sum_sales_lweek,0) 'lastyear_sum_sales_lweek',
       isnull(a.sum_nb,0) 'lastyear_sum_nb',
       isnull(a.sum_nos,0) 'lastyear_sum_nos',
from
(select store,
        sum(endprice*nb) as sum_sales_lweek,
        sum(nb) as sum_nb,
        count(distinct nos) as sum_nos
 from [CMD].[dbo].[cmd_xjjx_sale]
 where outdate>=@begindate and outdate<=@enddate and endprice>0
 group by store) a
left join
(select store,
        sum(endprice*nb) as sum_sales_lweek,
        sum(nb) as sum_nb,
        count(distinct nos) as sum_nos
 from [CMD].[dbo].[cmd_xjjx_sale]
 where outdate>=convert(varchar,dateadd(yyyy,-1,@begindate),112) 
 and outdate<=convert(varchar,dateadd(yyyy,-1,@enddate),112) and endprice>0
 group by store) b on a.store=b.store

------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:


你的意思是只对b那个子查询来分页,而不是对于整个查询来分页啊

是对整个查询来分页


试试这个:
declare @page_size int;
declare @page_num int;
 
--比如:每页10条记录
set @page_size = 10;
 
--比如:先取第1页
set @page_num = 1;

select *
from 
(
    select  a.dbno, a.names,a.qsq,a.class2,a.area_no,b.sum_sales_lweek,b.sum_nb,b.sum_nos,b.last_