日期:2014-05-18 浏览次数:20550 次
declare @khxx表 table (客户帐号 int,客户名称 varchar(4),年龄 int,购买数量 int) insert into @khxx表 select 10251026,'张三',25,20 union all select 10251256,'王鸣',36,50 union all select 10251649,'李名',52,150 union all select 10256524,'王三',60,30 union all select 10253625,'李六',78,52 SELECT '30<N<=50' AS [年龄(N)] , SUM(CASE WHEN 年龄 BETWEEN 31 AND 50 AND 购买数量 BETWEEN 21 AND 60 THEN 1 ELSE 0 END) AS [客户数量1(要求:20<P<=60)] , SUM(CASE WHEN 年龄 BETWEEN 31 AND 50 AND 购买数量 > 60 THEN 1 ELSE 0 END) AS [客户数量2(要求:60<P)] FROM @khxx表 UNION ALL SELECT '50<N' , SUM(CASE WHEN 年龄 > 50 AND 购买数量 BETWEEN 21 AND 60 THEN 1 ELSE 0 END) , SUM(CASE WHEN 年龄 > 50 AND 购买数量 > 60 THEN 1 ELSE 0 END) FROM @khxx表 /* 年龄(N) 客户数量1(要求:20<P<=60) 客户数量2(要求:60<P) -------- ------------------ -------------- 30<N<=50 1 0 50<N 2 1 */
------解决方案--------------------
/*
客户帐号 客户名称 年龄 购买数量
10251026 张三 25 20
10251256 王鸣 36 50
10251649 李名 52 150
10256524 王三 60 30
10253625 李六 78 52
要求: 年龄:N ; 购买数量:P
按年龄及购买数量分档次填写下表,
如年龄在50岁以上且购买数量在60以上的客户数量是多少?
下表如何写代码?
年龄(N) 客户数量1(要求:20<P<=60) 客户数量2(要求:60<P)
*/
go
if OBJECT_ID('tbl') is not null
drop table tbl
go
create table tbl(
cusid char(8),
cusname varchar(20),
cusage int,
cusamount int
)
go
insert into tbl
select 10251026,'张三',25,20 union all
select 10251256,'王鸣',36,50 union all
select 10251649,'李名',52,150 union all
select 10256524,'王三',60,30 union all
select 10253625,'李六',78,52
select '30<N<=50',
SUM(case when cusage between 31 and 50
and cusamount between 21 and 60
then 1 else 0 end) as [客户数量1(要求:20<P<=60)] ,
SUM(case when cusage between 31 and 50 and cusamount > 60
then 1 else 0 end) as [客户数量2(要求:60<P)]
from tbl
union all
select '50<N' ,
SUM(case when cusage > 50
and cusamount between 21 and 60 then 1 else 0 end),
SUM(case when cusage > 50 and cusamount > 60 then 1 else 0 end)
from tbl
结果:
(无列名) 客户数量1(要求:20<P<=60) 客户数量2(要求:60<P)
30<N<=50 1 0
50<N 2 1