日期:2014-05-18  浏览次数:20470 次

帮忙求一个存储过程
18岁以下 18-25岁
0元 ?人 ?人
1-500元 ?人 ?人

-------------------------------------------------

member表
mem_num , birthday

order表
ord_num,mem_num,price
-------------------------------------------------
我想要查出 18岁以下 购买0元的 有多少人
  18-25岁 购买1-500元的 有多少人
  18岁以下 购买0元的 有多少人
  18-25岁 购买1-500元的 有多少人
一起查出来 大家有没有什么好的办法???

------解决方案--------------------

/*
18岁以下 18-25岁
0元 ?人 ?人
1-500元 ?人 ?人

-------------------------------------------------

member表
mem_num , birthday

order表
ord_num,mem_num,price
-------------------------------------------------
我想要查出 
18岁以下 购买0元的 有多少人
18-25岁 购买1-500元的 有多少人
一起查出来 大家有没有什么好的办法???
*/
go
if OBJECT_ID('member')is not null
drop table member
go
create table member(
mem_num int,
birthday datetime
)
go
insert member
select 1,'1989-10-02' union all
select 2,'1996-11-21' union all
select 3,'1995-09-12' union all
select 4,'1988-12-09'

go
if OBJECT_ID('[order]')is not null
drop table [order]
go
create table [order](
ord_num int,
mem_num int,
price int
)
go
insert [order]
select 1,1,300 union all
select 2,1,50 union all
select 3,2,200 union all
select 4,3,0 union all
select 5,4,1000
go
;with T
as
(
select member.mem_num,
DATEDIFF(YY,birthday,GETDATE()) as age,[order].ord_num,
isnull([order].price,0) as price from member
left join [order] on member.mem_num=[order].mem_num
),
M
AS
(
select case when T.price=0 then 0 when T.price between 1 and 500 then 500 end as 价钱,
sum(case when age<18 then 1 else 0 end) as [18岁以下],
sum(case when age between 18 and 25 then 1 else 0 end) as [18岁到25岁]
from T group by price 
),
N
AS
(
select '购买'+CAST(价钱 as varchar)+'元' AS 范围,
SUM(CASE WHEN [18岁以下]=1 THEN 1 ELSE 0 END) AS [18岁以下],
SUM(CASE WHEN [18岁到25岁]=1 THEN 1 ELSE 0 END) AS [18岁到25岁]
from M
group by 价钱
)
 
SELECT *FROM N WHERE 范围 is not null
 
/*
范围 18岁以下 18岁到25岁
购买0元 1 0
购买500元 1 2
*/