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

多表查询求统计,求sql语句
有三个表:A,B,C
A表保存会员信息,包括ID,会员等级(1,2,3,4)等
B表保存会员购买信息(购买金额)
C表保存会员登录时间(类型datetime)
每个表都有会员的ID,求今年2月后还有登录记录并且消费大于10块各个等级会员的个数和2月后没有登录过的记录

------解决方案--------------------
SQL code


--今年2月后还有登录记录并且消费大于10块各个等级会员的个数
SELECT 会员等级,COUNT(1) AS num
FROM a INNER JOIN B ON A.Id = B.Id AND B.购买金额 > 10
INNER JOIN C ON A.Id = C.id AND 登录时间 > RTRIM(DATEPART(YEAR,GETDATE())) + '-03-01 0:00:00'
GROUP BY 会员等级

--2月后没有登录过的记录
SELECT ID,会员等级
FROM a 
WHERE NOT EXISTS (SELECT 1 FROM C WHERE A.Id = C.id AND 登录时间 > RTRIM(DATEPART(YEAR,GETDATE())) + '-03-01 0:00:00')

------解决方案--------------------
SQL code

-- 各个等级会员的个数
select Level, count(1)
from A
left join (
  select userID
  from B
  group by userID
  -- 消费大于10
  having sum(amount)>10
) as b on a.ID = b.userID
where 1=1
-- 今年2月后还有登录记录
and exists (select 1 from C where c.userID = a.ID
    and c.logintime >= '2012-02-01')
group by Level