更好的以下SQL的优化版本

时间:2015-08-25 12:04:10

标签: sql oracle query-optimization union

目前我已经创建了这个SQL查询:

select "Col1",
       "Col2",
       max(Col3) as "Col3"
  from (select Col1, Col2, 0 as "Col3" 
          from table1
         where col1='abc'

        union

        select Col1, Col2, count(Col3) as "Col3"
          from table1,
              (select table1.col1, count(table2.Col3) 
                 from table1, table2 
                where table1.col1 = table2.col1 
                group by table1.col1) 
      ) All_Records
where ALL_Records.Col1 = 'abc'
group by "Col1", "Col2"

有没有更好的方法来优化sql select语句,我想得到最大值,因为如果我不使用,我最终将为同一行的2行0(硬编码)和另一个值由逻辑返回。

问题陈述:我想检索员工薪水变化的次数, 如果SALARY_HISTORY显示0中没有行,我正在使用union来获取SALARY_HISTORY表中有条目的记录。

select "EMPID",max(SALARY_CHANGE_RECORDS.Salary_Change_Count)
    select EMP.ID as "EMPID",SALARY_CHANGE.Change_Count as "Salary_Change_Count"
    from 
    EMP,
    (select EMP.ID, COUNT(SALARY.Salary_Change_ID) as "Salary_Change_Count"
        from EMP, SALARY_HISTORY  where EMP.ID=SALARY_HISTORY.ID group by EMP.ID
    union 
    select EMP.ID, 0 as "Change_Count"from EMP) SALARY_CHANGE_RECORDS
group by "EMPID" 

1 个答案:

答案 0 :(得分:1)

在我看来,这样可行:

select    emp.id,
          count(salary_history.Salary_Change_ID)
from      emp
left join salary_history on emp.id = salary_history.id
group by  emp.id

它只计算salary_history记录的数量。

相关问题