0

我有一个典型的问题。

我需要修改下面的 T SQL 查询。目前它只在一张表中查找信息。我需要查看两个具有相同列的表以获取信息。一张表包含当前员工,一张包含前员工

SELECT t.net_Id
      ,e.fname
      ,e.lname
FROM tblTrackingEmployee t
    join view_employee e 
        on e.net_id = t.net_id
where trackingid = @trackingId
and empType = @empType

我想做的是使用联合来查看两者。员工要么出现在一个表中,要么出现在另一个表中,它永远不会出现在两个表中。

SELECT t.net_Id
      ,e.fname
      ,e.lname
FROM tblTrackingEmployee t
    JOIN view_employee e
        ON e.net_id = t.net_id
WHERE trackingid = @trackingId
AND empType = @empType
union 
SELECT t.net_Id
      ,fe.fname
      ,fe.lname
FROM tblTrackingEmployee t
      JOIN view_employee fe 
             ON fe.net_id = t.net_id
WHERE trackingid = @trackingId
AND empType = @empType

然而,这是一个转折点,我需要知道返回的人是现任还是前任员工。有没有办法在返回的表中添加一列,如果它是当前员工,则为 1,如果是前员工,则为 0?每个 trackingId 都可能包含两种类型的员工。

4

3 回答 3

2

为每个子句添加一个常量列SELECT- 您可以给它起别名:

SELECT t.net_Id
      ,e.fname
      ,e.lname
      ,'Current' AS Type
FROM tblTrackingEmployee t
    JOIN view_employee e
        ON e.net_id = t.net_id
WHERE trackingid = @trackingId
AND empType = @empType
union 
SELECT t.net_Id
      ,fe.fname
      ,fe.lname
      ,'Former'
FROM tblTrackingEmployee t
      JOIN view_formerEmployee fe 
             ON fe.net_id = t.net_id
WHERE trackingid = @trackingId
AND empType = @empType
于 2012-07-06T20:28:51.983 回答
1

让我直截了当地说,你有两张表,一张有现任员工,一张有前任员工?这是一个坏主意,您本来可以拥有一个状态为(“活动”/“非活动”)的表。无论如何,只需int为每个查询添加一个字段,例如

SELECT
 0 AS TheField,
  ....
FROM
  Table
UNION ALL
SELECT
1 AS TheField,
 ...
FROM
  table
于 2012-07-06T20:30:37.357 回答
1

如果您愿意,还可以按状态排序:

 SELECT U.* FROM
 (
  SELECT t.net_Id AS ID
      ,e.fname AS FName
      ,e.lname AS LName
      ,'Current' AS EmployStatus
  FROM tblTrackingEmployee t
      JOIN view_employee e
          ON e.net_id = t.net_id
  WHERE trackingid = @trackingId
  AND empType = @empType
  union 
  SELECT t.net_Id AS ID
      ,fe.fname AS FName
      ,fe.lname AS LName
      ,'Former' AS EmployStatus
  FROM tblTrackingEmployee t
        JOIN view_formerEmployee fe
               ON fe.net_id = t.net_id
  WHERE trackingid = @trackingId
    AND empType = @empType
) AS U
 ORDER BY U.EmployStatus
于 2012-07-06T20:31:08.630 回答