-1

我们如何为以下要求编写一个很好的查询。

我有一个employee表,它有 3 列

1. Employee ID
2. ManagerID
3. LocationID

我想返回首先返回的输出(1 或 2 或 3 或 4 或无)。以下是附加条件。

1. EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333
2. EmployeeID = 1233 and ManagerID is null and LocationID = 3333
3. EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333
4. EmployeeID = 1233 and ManagerID is null and LocationID is null

我想有这样的逻辑。谁能帮我查询一下。

4

4 回答 4

0

也许是这样:

SELECT * FROM employee
WHERE EmployeeID = 1233 
AND (ManagerID = 2222 OR ManagerID IS NULL)
AND (locationID = 3333 OR locationID IS NULL);
于 2013-11-13T21:32:24.563 回答
0

记住 Sql Server 中的运算符优先级,Sql Server 检查/过滤结果的顺序为 NOT-->And-->OR ,当你有很多条件要检查时会有点混乱,所以最好使用括号将条件分解成更小的部分,这样更易​​读,更易于维护和调试。

SELECT EmployeeID, ManagerID, LocationID
FROM employee
WHERE EmployeeID  = 1233 
AND (ManagerID = 2222 OR ManagerID IS NULL) 
AND (LocationID = 3333 OR LocationID IS NULL)
于 2013-11-13T21:32:28.790 回答
0

也许这个,不能从你的问题中看出

SELECT  * FROM employee
ORDER BY 
CASE WHEN EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333 THEN 0 ELSE 1 END,
EmployeeID = 1233 and ManagerID is null and LocationID = 3333 THEN 1 ELSE 2 END,
EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333 THEN 2 ELSE 3 END,
EmployeeID = 1233 and ManagerID is null and LocationID is null THEN 3 ELSE 4 END
于 2013-11-13T21:37:27.817 回答
0

感谢您分享您的想法的所有帮助。

这是我使用的一种解决方案。

Select * from (
Select * from Employee where EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333;
Union 
Select * from Employee where EmployeeID = 1233 and ManagerID is null and LocationID = 3333
Union
Select * from Employee where  EmployeeID = 1233 and ManagerID = 2222 and LocationID = 3333
Union
Select * from Employee where  EmployeeID = 1233 and ManagerID is null and LocationID is null
) z where z.rownum = 1

这对我的场景很有效。如果您发现任何好主意,请发帖给我。

于 2013-12-03T02:33:59.620 回答