我对视图创建有疑问。
这是我的问题:
我需要使用视图生成报告,该视图从两个表中获取数据,例如Table_A和Table_B。
Table_A中的示例数据:
empno empname
----------------
1 abc
2 xyz
表_B中的示例数据:
Empno element_name Amount
--------------------------------
1 Basic_Salary 10000
1 Medical_bill 500
2 Basic_Salary 20000
2 Medical_bill 500
现在,我的预期结果是
输出:
Empno Empname Basic_Salary Medical_bill Total_sum
--------------------------------------------------------------------------
1 abc 10000 500 10500
2 xyz 20000 500 20500
注1:
我通过传递季度报告或月度报告等参数来生成报告。
假设这里可以说,我需要3个月的详细报告 我需要总结员工的基本工资
请帮助我。
非常感谢!
答案 0 :(得分:1)
您可以使用以下查询:
---Table data preparation
with tabl_A (empno, empname, effective_date, elem_name )
as
( Select 1 , 'abc', '13-jun-2016', 'Basic_Salary' from dual
UNION ALL
Select 1 , 'abc', '13-jun-2016', 'Medical_Bill' from dual
UNION ALL
Select 2, 'xyz', '5-may-2017', 'Basic_Salary' from dual
UNION ALL
Select 2, 'xyz', '5-may-2017', 'Medical_Bill' from dual ),
tabl_B ( Empno ,Basic_Salary, Medical_Bill) as
(
select 1, 20000, 500 from dual
UNION ALL
select 2 , 50000, 500 from dual
),
---Table data preparation over
tabl_c (empno, empname, effective_date,sal,mbill ) as
(
SELECT A.empno,
A.empname,
A.effective_date,
b.Basic_Salary * &num_mnth AS sal,
b.Medical_Bill * &num_mnth AS mbill
FROM tabl_A A
INNER JOIN tabl_B B
ON a.empno = b.empno
GROUP BY A.empno,
A.empname,
A.effective_date,
b.Basic_Salary,
b.Medical_Bill )
SELECT c.*, (sal + mbill) AS Total_Sum
FROM tabl_c c;
执行时,会要求输入月份作为输入,然后显示结果。
输出:
SQL> /
Enter value for num_mnth: 3
old 22: b.Basic_Salary * &num_mnth AS sal,
new 22: b.Basic_Salary * 3 AS sal,
Enter value for num_mnth: 3
old 23: b.Medical_Bill * &num_mnth AS mbill
new 23: b.Medical_Bill * 3 AS mbill
EMPNO EMP EFFECTIVE_D SAL MBILL TOTAL_SUM
---------- --- ----------- ---------- ---------- ----------
1 abc 13-jun-2016 60000 1500 61500
2 xyz 5-may-2017 150000 1500 151500
答案 1 :(得分:1)
在您回复我的评论之后...我建议您更新数据模型,这样您就可以获得一份员工表和一个包含值的元素表(纯粹主义者可以更进一步,有三个表 - 员工,元素和emp_element_values)。这意味着您可以在不知道或关心元素表的情况下更新员工数据(此时更改名称将导致对tableA的多次更新,而这不是您想要的。
WITH
emp (empno, empname) AS
(SELECT 1,'abc' FROM dual UNION ALL
SELECT 2, 'xyz' FROM dual
)
,elements (empno, element_name, element_value) AS
(SELECT 1,'Basic_Salary',20000 FROM dual UNION ALL
SELECT 1,'Medical_Bill',500 FROM dual UNION ALL
SELECT 2,'Basic_Salary',50000 FROM dual UNION ALL
SELECT 2,'Medical_Bill',1000 FROM dual
)
SELECT
emp.empno
,emp.empname
,sal.element_value * :number_of_months basic_salary
,med.element_value * :number_of_months medical_bill
FROM
emp
,elements sal
,elements med
WHERE 1=1
AND emp.empno = sal.empno
AND sal.element_name = 'Basic_Salary'
AND emp.empno = med.empno
AND med.element_name = 'Medical_Bill'
;
所以,在上面我没有包含effective_date,因为我不知道这是emp还是元素的属性。