我有一个典型的问题。
我需要修改以下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都可能包含两种类型的员工。
答案 0 :(得分: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
答案 1 :(得分:1)
让我直截了当地说,你有两张桌子,一张是现任员工,一个是前雇员?这是一个坏主意,你可能已经有一个状态表('活动'/'无效')。在任何情况下,只需添加一个字段,如int
,您想要每个查询
SELECT
0 AS TheField,
....
FROM
Table
UNION ALL
SELECT
1 AS TheField,
...
FROM
table
答案 2 :(得分: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