[英]SQL: select rows from a certain table based on conditions in this and another table
[英]Oracle SQL Converting Rows into Columns and Giving them Values from another Table based on Conditions from another Table
我有列emp_id
和emp_name
的表employees
,包含列person_id
和element_name
的表elements
,例如Basic Salary
,以及包含列value_result
的表values
,例如1500
並且還包含不需要的垃圾數據,為了擺脫它我需要使用包含列value_type
的表values_type
,
select element_name , // e.g. Basic Salary
values // e.g. 1500,
emp_name // john
from values,values_type, elements,employees
join elements on elements.emp_id= employees.emp_id
and element_name IN ('Basic Salary', 'Transportation Allowance')
join values on values.element_id = elements.element_id
join values_type on values_type.value_id = values.value_id
and values_type.value_type = 'Amount` // in order to give me desirable values in numbers
這工作正常,但它會給我每個employee
2 行,一個用於Basic Salary
,一個用於Transportation Allowance
,我想要的是從element_name
行中制作 2 列,這些是Basic Salary
和Transportation Allowance
,然后我想帶根據表values_type
中的條件types.value_type = 'Amount`
,每列下的表values
中的相關行( values
),我該如何實現?
樣本結果
emp_id element_name values
1 Basic Salary 1500
1 Transportation Allowance 200
想要的結果
emp_id Basic Salary Transportation Allowance
1 1500 200
為了在列上使用不同的條件,我嘗試連接表values
2 次:
select element_name , // e.g. Basic Salary
v1.values, // e.g. 1500 ( basic salary )
v2.values, // e.g. 200 ( transportation allowance )
emp_name, // john
from values,values_type, elements,employees
join elements on elements.emp_id= employees.emp_id
and element_name IN ('Basic Salary', 'Transportation Allowance')
left outer join values v1 on v1.values.element_id = elements.element_id
left outer join values v2 on v2.values.element_id = elements.element_id
join values_type on values_type.value_id = values.value_id
and values_type.value_type = 'Amount` // in order to give me desirable values in numbers
但隨后我需要將values_type
加入到每個值中:
join values_type t1 on t1.values_type.value_id = v1.values.value_id
and t1.value_type = 'Amount` // in order to give me desirable values in numbers
join values_type t2 on t2.values_type.value_id = v2.values.value_id
and t2.value_type = 'Amount` // in order to give me desirable values in numbers
這當然行不通,它會給出空結果,我已經堅持了 2 天了..
可能是這樣的
select emp_id, // e.g. Basic Salary
sum(decode(element_name,'Basic Salary',values,0)) Basic_Salary,
sum(decode(element_name,'Transportatiion Allowance',values,0)) Transportation_Allowance
from values,values_type, elements,employees
join elements on elements.emp_id= employees.emp_id
and element_name IN ('Basic Salary', 'Transportation Allowance')
join values on values.element_id = elements.element_id
join values_type on values_type.value_id = values.value_id
and values_type.value_type = 'Amount'
group by emp_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.