簡體   English   中英

where 子句中的表列值

[英]Table Column value in where clause

我有兩張桌子

員工

員工ID 姓名 工作
123 大衛 是的
124 提摩太 是的
125 馬克西
126 阿比

員工宿舍

ID 員工ID EmployeeSpclField EmployeeSpclValue
1 123 已婚 是的
2 123 國籍 墨西哥
3 123 工作 鉗工
4 124 已婚 是的
5 124 國籍 ARG
6 125 工作 司機

我需要一個基於 Bind 值 Employee id 返回 1 或 0 的 Sql 查詢,我需要驗證以下條件

  1. 工作不應為空 2)國籍不應為空且他應屬於 MEX

那我該怎么做呢? 我正在建造這樣的東西

select 1 from Employee emp ,EmployeeResidence er 
where 
employeeid=:empid and emp.job is not null and 

我正在努力包含 EmployeeSpclField 列值來檢查它是否不為 null 並且屬於 MEX

我可能會避免加入,而是在此處使用存在邏輯:

SELECT e.*
FROM Employee e
WHERE Job IS NOT NULL AND
      EXISTS (SELECT 1 FROM EmployeeResidence er
              WHERE er.EmployeeId = e.EmployeeId AND
                    er.EmployeeSpclField = 'Nationality' AND
                    er.EmployeeSpclValue = 'MEX');

選擇一個 0/​​1 標志

select case when exists (
    select 1 
    from Employee emp 
    join EmployeeResidence er 
      on emp.employeeid = er.employeeid and er.EmployeeSpclField = 'Nationality' and er.EmployeeSpclValue = 'MEX'
    where emp.employeeid=:empid and emp.job is not null ) then 1
   else 0 end flag 
from dual;

嘗試這個:

Select
e.EmployeeID,
case when er.EmployeeID is null then 0 else 1 end as return_val
from
Employee e
left outer join
(select EmployeeId,
 max(case when EmployeeSpclField='Married' then EmployeeSpclValue else NULL end) as married,
 max(case when EmployeeSpclField='Nationality' then EmployeeSpclValue else NULL end) as Nationality,
 max(case when EmployeeSpclField='Job' then EmployeeSpclValue else NULL end) as Job
from 
 EmployeeResidence
group by
EmployeeId) er
on e.EmployeeId=er.EmployeeId
and e.Job is not null 
and (er.Nationality is not null and er.Nationality ='MEX')

一種選擇可能是使用條件聚合來計算所需的條件

SELECT SIGN(NVL(SUM(CASE WHEN er.EmployeeSpclField = 'Nationality' 
                          AND er.EmployeeSpclValue = 'MEX' 
                          AND e.Job IS NOT NULL THEN 1 ELSE 0 END),0)) 
    AS Result
  FROM Employee e
  JOIN EmployeeResidence er
    ON er.EmployeeId = e.EmployeeId
 WHERE e.EmployeeId = :empid

其中SIGN()函數是用來考慮可能有重復的記錄Nationality的價值EmployeeSpclField每任何列EmployeeId列的值。

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM