SQL Server查询逻辑

时间:2013-11-13 21:27:53

标签: sql sql-server

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

我有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 个答案:

答案 0 :(得分:0)

也许这个:

SELECT * FROM employee
WHERE EmployeeID = 1233 
AND (ManagerID = 2222 OR ManagerID IS NULL)
AND (locationID = 3333 OR locationID IS NULL);

答案 1 :(得分:0)

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

SELECT EmployeeID, ManagerID, LocationID
FROM employee
WHERE EmployeeID  = 1233 
AND (ManagerID = 2222 OR ManagerID IS NULL) 
AND (LocationID = 3333 OR LocationID IS NULL)

答案 2 :(得分: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

答案 3 :(得分: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

这适用于我的场景。如果你发现任何好主意,请发帖给我。