27,580
社区成员
发帖
与我相关
我的任务
分享
SELECT SUM(CASE WHEN YEARTYPE = 'TY' THEN TOTAL ELSE 0 END) AS 'thisyeartotal',
SUM(CASE WHEN YEARTYPE = 'LY' THEN TOTAL ELSE 0 END) AS 'lastyeartotal'
FROM TB
GROUP BY SHOP_ID
---------------------------------------------
--> Author : js_szy
--> Target : 各位大大,小卒就是想要一朵花
--> Date : 2009-12-02 12:13:53
--> Version: SQL Server 2005
---------------------------------------------
--> 测试数据: @tb
declare @tb table (shop_id int,Total int,yeartype varchar(2),time datetime)
insert into @tb
select 1,10,'ty','2009-12-01' union all
select 1,25,'ly','2008-12-01' union all
select 2,15,'ty','2009-12-01' union all
select 2,32,'ly','2008-12-01' union all
select 3,200,'ty','2009-12-01' union all
select 3,23,'ly','2008-12-01'
select
shop_id,
thisyeartotal=sum(case when yeartype='ty' then Total else 0 end),
lastyeartotal=sum(case when yeartype='ly' then Total else 0 end)
from @tb
group by
shop_id
shop_id thisyeartotal lastyeartotal
----------- ------------- -------------
1 10 25
2 15 32
3 200 23
(3 行受影响)
select
sum(case when year([time])=2009 then Total else 0 end) as thisyeartotal,
sum(case when year([time])=2008 then Total else 0 end) as lastyeartotal
from
tb
group by
shop_id
select sum(case when year(time)=year(getdate()) then Total else 0 end) as thisyeartotal,
sum(case when year(time)=year(getdate())-1 then Total else 0 end) as lastyeartotal
from tab
where time >= convert(varchar(5),dateadd(year,-1,getdate()),120)+'01-01'
and time < convert(varchar(5),dateadd(year,1,getdate()),120)+'01-01'
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([shop_id] int,[Total] int,[yeartype] varchar(2),[time] datetime)
insert [TB]
select 1,10,'ty','2009-12-01' union all
select 1,25,'ly','2008-12-01' union all
select 2,15,'ty','2009-12-01' union all
select 2,32,'ly','2008-12-01' union all
select 3,200,'ty','2009-12-01' union all
select 3,23,'ly','2008-12-01'
select thisyeartotal=max(case when datediff(yy,getdate(),time)=0 then Total else 0 end),
lastyeartotal=max(case when datediff(yy,getdate(),time)=-1 then Total else 0 end)
from [TB]
group by shop_id
/*
thisyeartotal lastyeartotal
------------- -------------
10 25
15 32
200 23
(所影响的行数为 3 行)
*/
drop table TB
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([shop_id] int,[Total] int,[yeartype] varchar(2),[time] datetime)
insert [TB]
select 1,10,'ty','2009-12-01' union all
select 1,25,'ly','2008-12-01' union all
select 2,15,'ty','2009-12-01' union all
select 2,32,'ly','2008-12-01' union all
select 3,200,'ty','2009-12-01' union all
select 3,23,'ly','2008-12-01'
select thisyeartotal=max(case when datediff(yy,getdate(),time)=0 then Total else 0 end),
lastyeartotal=max(case when datediff(yy,getdate(),time)=0 then Total else 0 end)
from [TB]
group by shop_id
/*
thisyeartotal lastyeartotal
------------- -------------
10 10
15 15
200 200
(所影响的行数为 3 行)
*/
drop table TB