tbale:a
(id,name)
ID  NAME
1    AA
tbale:b(
id,
a_id,//表a的ID
a_date,//日期
times,//次数
type)//类型(有1和2)ID   A_ID      A_DATE      TIMES  TYPE
1     1       2007-1-31      33     1
2     1       2007-1-31      23     2
3     1       2007-1-30      65     1
4     1       2007-1-30      34     2
5     1       2007-1-29      32     1
6     1       2007-1-29      88     2根据A表的ID查询如下结果
ID  NAME   TYPE1_TODAY TYPE1_YESTERDAY    TYPE2_TODAY   TYPE2_YESERDAY   TYPE1_SUM TYPE2_SUM 
1    AA         33          65                 23        34               130      145

解决方案 »

  1.   

    select a.id,a.name
    sum(case when (b.a_date = trunc(sysdate) and b.type = 1) then b.times else 0 end) as "TYPE1_TODAY",
    sum(case when (b.a_date = trunc(sysdate)-1 and b.type = 1) then b.times else 0 end) as "TYPE1_YESTERDAY",
    sum(case when (b.a_date = trunc(sysdate) and b.type = 2) then b.times else 0 end) as "TYPE2_TODAY",
    sum(case when (b.a_date = trunc(sysdate)-1 and b.type = 2) then b.times else 0 end) as "TYPE2_YESERDAY",
    sum(case when b.type = 1 then b.times else 0 end) as "TYPE1_SUM",
    sum(case when b.type = 2 then b.times else 0 end) as "TYPE2_SUM",
    from a,b
    where a.id=b.a_id
    group by a.id,a.name;
      

  2.   

    select a.* , sum(case when a.type=1 and a.date=to_char(sysdate,'yyyy-mm-dd') then b.times end) TYPE1_TODAY ,sum(case when a.type=1 and a.date=to_char(sysdate-1,'yyyy-mm-dd') then b.times end) TYPE1_YESTERDAY ,sum(case when a.type=2 and a.date=to_char(sysdate,'yyyy-mm-dd') then b.times end) TYPE2_TODAY ,sum(case when a.type=2 and a.date=to_char(sysdate-1,'yyyy-mm-dd') then b.times end) TYPE2_YESTERDAY ,sum(case when a.type=1 then b.times end) TYPE1_SUM ,sum(case when a.type=2 then b.times end) TYPE2_SUM  from a , b where a.id=b.aid group by a.id,a.name
      

  3.   

    上面这个语句没有看到b.a_date 是日期格式以为是文本格式,还误把b 的字段写成a的字段 发出之后才看到yyy21() 已经回复过,并且写的非常整洁, sum(case when b.type=1 and b.adate=trunc(sysdate) then b.times end) 其实不用else 0