PL / SQL块查询 - 显示总计,最大值,最小值和平均值

时间:2016-11-16 17:23:19

标签: sql database oracle plsql oracle11g

我是PL / SQL的新手,需要弄清楚以下问题。如果有人可以帮我查询,我将不胜感激。这样我就可以了解问题的构成。

我想创建一个新的匿名PL / SQL块,它将显示公司中的员工总数,他们的最高工资,最低工资和平均工资,平均工资四舍五入到整数。

这是对的吗?

SELECT ROUND(MAX(salary),0) 'Maximum',  
ROUND(MIN(salary),0) 'Minimum',  
ROUND(SUM(salary),0) 'Sum',  
ROUND(AVG(salary),0) 'Average'  
FROM employees;  

PL / SQL让我困惑

2 个答案:

答案 0 :(得分:1)

引号有问题:在列别名中,如果需要,您只能使用",或者只是简单地定义没有引号的别名;不同之处在于,例如:

SQL> SELECT count(employee_id) as "Number of employees", -- double quotes: this alias will keep the case of my string and have spaces
  2  ROUND(MAX(salary),0) "Maximum",
  3  ROUND(MIN(salary),0) "Minimum",
  4  ROUND(SUM(salary),0) Sum, -- no quotes: this will be in UPPERCASE and you can have no spaces
  5  ROUND(AVG(salary),0) Average
  6  FROM employees;

Number of employees    Maximum    Minimum        SUM    AVERAGE
------------------- ---------- ---------- ---------- ----------
                107      24000       2100     691416       6462

此外,确切地说,这是一个SQL查询,而以下是PL / SQL块:

declare
    vCount number;
    vMax number;
    vMin number;
    vSum number;
    vAvg number;
begin  
    SELECT count(employee_id) as "Number of employees", 
    ROUND(MAX(salary),0) "Maximum",
    ROUND(MIN(salary),0) "Minimum",
    ROUND(SUM(salary),0) Sum, 
    ROUND(AVG(salary),0) -- you need no aliases here
    into vCount,
         vMax,
         vMin,
         vSum,
         vAvg
    FROM employees;
    --
    dbms_output.put_line('Count: ' || vCount || ' - ' || 
                            'Max: ' || vMax || ' - ' ||
                            'Min: ' || vMin || ' - ' ||
                            'Sum: ' || vSum || ' - ' ||
                            'Avg: ' || vAvg);
end;

答案 1 :(得分:-1)

这个问题并非100%明确,但您说公司需要这个问题,而且您还需要每个公司的员工人数?我猜你的表包含像nCompanyID这样的字段?

然后你有:

SELECT
    nCompanyID as Company -- I don't know if you have an ID or a string for it...
    COUNT(*) as nbEmployees,
    ROUND(MAX(salary),0) as MaximumSalary,
    ROUND(MIN(salary),0) as MinimumSalary,
    ROUND(SUM(salary),0) as TotalSalary,
    ROUND(AVG(salary),0) as AverageSalary
FROM employees
GROUP BY nCompanyID;

请注意,这是在MS SQL Server中,但我确信oracle的SQL对于这类事情具有几乎相同的语法。