1

I am writing a query in which where clause have IN clause and there are large number of values in this IN clause , I want to fetch the result such that if there is no value exist in table for value given in IN clause then a raw containing 0 or null should return for that value. for example..

select age,sex,date_joining from emp where name IN ('amit','john','paul','dilip')

Now assume for this query ,data for john and paul does not exist in database then result should be like below..

21    male   21-AUG-2011
null  null   null
null  null   null
25    male   9-aug-2010

we can also have 0 instead of null if null is not possible

Thanks...

4

2 に答える 2

4
select  filter.name
,       emp.age
,       emp.sex
,       emp.date_joining 
from    (
        values ('amit'), ('john'), ('paul'), ('dilip')
        ) filter(name)
left join    
        emp
on      emp.name = filter.name

Live example at SQL Fiddle.

For older values of SQL Server, replace the line with values by:

from    (
                  select 'amit'
        union all select 'john'
        union all select 'paul'
        union all select 'dilip'
        ) filter(name)
于 2012-11-05T14:29:41.267 に答える
0

共通テーブル式を使用して、次の結果を取得することもできます。

;With AllEmpDetails as
(
Select [Name] from emp
UNION Select 'amit' 
UNION Select 'john' 
UNION Select 'paul' 
UNION Select 'dilip'
)Select AllEmpDetails.Name, e2.Age, e2.Sex, e2.date_joining 
from AllEmpDetails 
Left Join emp e2 on e2.[Name] = AllEmpDetails.Name

私のデータベースには、すでにamitdilipの詳細を追加しているのでUNION、利用可能な従業員の詳細を簡単に取得できるため、使用しました。一方、で使用できUNION ALLますDistinct

于 2012-11-05T18:52:39.960 に答える