如何在下面的查询中使用group by功能?

时间:2014-05-08 13:44:38

标签: sql group-by

如何使用以下查询功能分组?

实际上我试图加入(内连接)两个表有2个字段。

这是好的:

t1.fiels6 = t2.field7 

这在内连接函数中不起作用。因此我在函数中使用了它:

t1.field8 = SUBSTRING(t2.field9,1,INSTR(t2.field9,'-') - 1) 
and (INSTR(t2.field9,'-') - 1) < 14 
and (INSTR(t2.field9,'-') - 1) > 0 

我的主要目标是为每组t2.field2获取avg((t1.field3 * t2.field4))和stddev((t1.field3 * t2.field4))

select 
    t1.field1 as f1, t2.field2 as f2,(t1.field3 * t2.field4) as f5 
from 
    pub.table1 t1, pub.table2 t2 
where 
    t1.fiels6 = t2.field7 
    and t1.field6 = 'XXX' 
    and t1.field8 = SUBSTRING(t2.field9,1,INSTR(t2.field9,'-') - 1) 
    and (INSTR(t2.field9,'-') - 1) < 14 and (INSTR(t2.field9,'-') - 1) > 0

1 个答案:

答案 0 :(得分:0)

将您拥有的内容移至内部选择和分组 -

select f2, avg(calced), atddev(calced)
from
(
  select 
    t1.field1 as f1, 
    t2.field2 as f2,
    (t1.field3 * t2.field4) as calced 
  from pub.table1 t1
  join pub.table2 t2 on t1.fiels6 = t2.field7 
                    and (INSTR(t2.field9,'-') - 1) < 14 
                    and (INSTR(t2.field9,'-') - 1) > 0
                    and t1.field8 = SUBSTRING(t2.field9,1,INSTR(t2.field9,'-') - 1) 
  where t1.field6 = 'XXX' 
) t
group by f2