根据字段值选择行

时间:2011-04-26 11:04:08

标签: sql sql-server sql-server-2005 tsql

我有两张桌子:员工和约会。

1员工可以有多个约会。 有一个字段:可见性可以容纳0,1或2.

  0: show any of the appointment, 
  1: Show this appointment only, 
  2: Don't show the appointment. 

现在我想选择员工和约会的记录:

  1. 如果可见性为1,则选择该记录而不是任何其他记录
  2. 如果可见性为0,则只选择一条记录,例如前1条
  3. 如果可见性为2,则为该记录选择空值,但员工ID除外。
  4. 有人能指出我如何使用Sql Server 2000完成它吗?

3 个答案:

答案 0 :(得分:0)

With SelectedAppointments AS
{
   SELECT * FROM Appointments WHERE Visibility <> 2 
}

SELECT  Employee.Id, < All columns of SelectedAppointments unless EmployeeId> 
   FROM Employee LEFT JOIN SelectedAppointments   
   on Employee.Id = SelectedAppointments.EmployeeId

答案 1 :(得分:0)

select *
from Employee as Emp
  left outer join
    (select top 1 *
     from Appointments
     where Visibility <> 2
     order by Visibility desc) as App
  on Emp.EmpID = App.EmpID    

答案 2 :(得分:0)

我做了几个假设。

  1. 可能有多个约会
  2. 如果你有1和0的约会,你想保证显示的是<1>。
  3. 您只能拥有1条

    的记录
    SELECT
        e.empid,
        COALESCE(OneAppoint.appointmentID, ZeroAppoint.appointmentID) appointmentID
    FROM
        employee e
        LEFT JOIN appointment ZeroAppoint
            INNER JOIN (
            SELECT
                max(a.appointmentid) appointmentid ,
            a.EmpID    
            FROM
                appointment a
            WHERE
                a.Visibility =0 
    
                ) maxZeroAppoint
            ON ZeroAppoint.appointmentid = maxZeroAppoint.appointmentid
        ON e.empID = ZeroAppoint.empID
        LEFT JOIN appointment OneAppoint
        ON e.empID = OneAppoint.empID 
            and OneAppoint.Visibility = 1