t_person   人员表
    pid   birthday
  
    100   1990-01-01
    101   1985-01-01
    102   1990-01-01
    103   1985-01-01t_sale  销售表
   pid    salemoney
   100     100
   100     200
   101     300
   101     400
   102     500
   102     600现在要求:
  根据年龄段来分组求销售总额 和这个年龄段的人数
比如结果表
   age   salevalue countvalue
    16    1400        2
    21     700        216是1990-01-01出生的人的年龄
1400是16岁的人销售总额
2是16岁的人数
这个sql语句怎么写
  select sum(ts.salemoney) as sprem,count(*) countvalue, 
Year(TO_DATE(now, '%Y-%m-%d')) - Year(TO_DATE(birthday, '%Y-%m-%d')) as age 
from t_person tp , t_sale  ts
group by Year(TO_DATE(now, '%Y-%m-%d')) - Year(TO_DATE(Birthday, '%Y-%m-%d'))用的是informix数据库,不过语法和oracle,ms sql应该没多大区别
   

解决方案 »

  1.   

    时间修改一下就ok
    to_char(sysdate,'YYYY')-to_char(birthday,'YYYY')
      

  2.   

    age   salevalue countvalue
        16    1400        2
        21     700        1
    只写出这种了,103那家伙什么也没卖,怎么处理呀~~
      

  3.   

    having by  啊
    把103筛选出来作为单独处理啊
      

  4.   

    select (2006-left(p.birthday,4)),sum(s.salemoney),count(distinct p.pid)
    from t_sale s,t_person p 
    where s.pid=p.pid 
    group by (2006-left(p.birthday,4))
    这个把日期当字符串写的,having怎么用呀?
      

  5.   

    select ps.age, sum(ps.salemoney), count(unique ps.pid)
      from(select t.pid, to_number(to_char(sysdate,'yyyy'))-to_number(to_char(t.birthday,'yyyy')) age,s.salemoney 
            from person t,sale s
            where t.pid = s.pid(+)) ps  
      group by ps.ageoracle 数据库
      

  6.   

    不用单独筛选pid为103的,因为是根据年龄分组,pid=103的属于年龄为21年龄段的了。
    having放在group by后面,当作条件处理了,与where一样。