how to write a column expression in a query based on other table value exist

  • Hello Please help me here.,

    i have below tables called

    student (sno, sname, address)

    StudentDrillEnrolled (sno, DrillClass)

    StudentDrillNotEnrolled (Sno, Reason, Viever)

    how to write a query, so that i will have sno,sname,address, Enrolled (Y/N/NA)

    enrolled will be calculated

    if sno exist in StudentDrillEnrolled table then Y

    if sno exist in StudentDrillNotEnrolled table then it is N

    if not exist in both tables enrolled & not enrolled then N/A

    please help me here

    Thanks in advance

    asitti

  • Sounds like you need a couple of left joins and a case - this should do...

    SELECT

    s.sno

    ,CASEWHEN e.sno IS NOT NULL THEN

    'Y'

    WHEN n.sno IS NOT NULL THEN

    'N'

    WHEN e.sno IS NULL AND n.sno IS NULL THEN

    'N/A'

    END

    FROM student s

    LEFT JOIN StudentDrillEnrolled e

    ON s.sno=e.sno

    LEFT JOIN StudentDrillNotEnrolled n

    ON s.sno=n.sno;

  • Or you can use EXISTS:

    SELECT

    sno, sname, address,

    CASE

    WHEN EXISTS(SELECT 1 FROM dbo.StudentDrillEnrolled sde WHERE sde.sno = s.sno) THEN 'Y'

    WHEN EXISTS(SELECT 1 FROM dbo.StudentDrillNotEnrolled sdne WHERE sdne.sno = s.sno) THEN 'N'

    ELSE 'N/A'

    END AS Enrolled

    FROM dbo.student s

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply