下面的更好的优化版本 SQL

Better optimized version of the below SQL

目前我已经创建了这个 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 table 中有条目的记录,如果 SALARY_HISTORY 中没有行,则显示 0.

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" 

我觉得这行得通:

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 条记录的数量。