我正在使用Oracle。我有表名的作品看起来像:
Company-name Employee-name salary
A1 Jim 122000
...
表2管理外观(经理管理自己)
Employee-name Manager-name
Jim John
Kate John
John John
我想以盈利=收入 - 总薪水返回公司,其中Revenue = Employee's salary * 3(此处,只有员工生成收入,而经理不生成)。这是我的代码
with Employee_count as(
Select a.company-name, b.employee-name as Guru
From works a
Inner join manages b
On a.employee-name=b.employee-name
Where b.employee-name<>b.manager-name
Group by a.company-name
)
Comput_revenue as (
select a2.company-name, SUM(3*a2.salary) as Revenue
from works a2
Inner join Employee_count b2
On a2.company-name=b2.company-name
Where a2.employee-name=b2.Guru
group by a2.company-name),
select a3.company-name, b3.Revenue-SUM(a3.salary) as Profit
from works a3 inner join Comput_revenue b3
On a3.company-name=b3.company-name;
我在这里有两个问题:
(1)每个子句的表名是否属于本地的别名?我应该使用a,a2,a3还是只使用a和b都可以?
(2)如果它是正确的,它仍然看起来太大了。有什么想简化吗?
答案 0 :(得分:2)
我希望,使用WITH子句并不是强制性的,因为我找到了一个更简单的解决方案:
<强>作品强>
COMPANY EMPLOYEE_NAME SALARY A1 Jim 122000 A1 Kate 132000 A1 John 88000 A2 Jack 96000 A2 Jason 134000 A2 Janet 138000
<强>管理强>
EMPLOYEE_NAME MANAGER_NAME Jim John Kate John John John Jack Janet Jason Janet Janet Janet
实现逻辑的查询是:
SELECT
COMPANY,
SUM(
DECODE(EMPLOYEE_NAME, MANAGER_NAME, 0, SALARY * 3) - SALARY
) AS PROFIT
FROM WORKS
INNER JOIN MANAGES USING(EMPLOYEE_NAME)
GROUP BY COMPANY
ORDER BY 2 DESC;
COMPANY PROFIT A1 420000 A2 322000
您的方法很好,但您开始专注于使用CTE(WITH子句)功能。
答案 1 :(得分:0)
或多或少符合ANSI SQL标准。只需将破折号更改为表格和列名称中的下划线,然后在第一个带有子句后添加逗号,并在第二个后删除。 (由SQL Validator验证的语法 http://developer.mimer.com/validator/parser200x/index.tml#parser)