在T-SQL中显示表的替代解决方案

时间:2011-05-04 11:40:42

标签: tsql sorting

我有一个简单的员工表,我希望以特定的顺序显示。我想知道是否有替代解决方案(或更好的解决方案)来实现相同的结果。 T-SQL脚本如下所示:

CREATE TABLE Employee(
 EmployeeID INT IDENTITY(1,1) NOT NULL,
 EmployeeName VARCHAR(255) NULL,
 ManagerID INT NULL,
 EmployeeType VARCHAR(20) NULL
)
GO

INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Brad',5,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('James',3,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Ray',null,'Manager');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Tom',8,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Neil',8,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Rob',5,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Paul',5,'Memeber');
INSERT INTO Employee (EmployeeName, ManagerID, EmployeeType)
VALUES ('Tim',null,'Manager');
GO
SELECT e.EmployeeType, e.EmployeeName AS [Team Member],    
  (SELECT e2.EmployeeName FROM Employee AS e2 WHERE e2.EmployeeID = e.ManagerID) AS Manager
FROM Employee AS e 
ORDER BY e.EmployeeType, e.EmployeeID

行首先由manger排序,然后是employeeID。我担心的是,在我的解决方案中,它按EmployeeType列排序。而不是通过ManagerId列对它进行排序会更好吗?因为EmployeeType将来可以更改,例如从Manager到Team Manager,这可能会导致不同的结果!

2 个答案:

答案 0 :(得分:1)

如果经理的标准是列ManangerID is null,您可以按顺序使用案例来获取经理。

SELECT e.EmployeeType, e.EmployeeName AS [Team Member],    
  (SELECT e2.EmployeeName FROM Employee AS e2 WHERE e2.EmployeeID = e.ManagerID) AS Manager
FROM Employee AS e 
ORDER BY CASE WHEN E.ManagerID IS NULL THEN 0 ELSE 1 END, e.EmployeeID

如果要根据EmployeeType设置排序,可以这样做

SELECT e.EmployeeType, e.EmployeeName AS [Team Member],    
  (SELECT e2.EmployeeName FROM Employee AS e2 WHERE e2.EmployeeID = e.ManagerID) AS Manager
FROM Employee AS e 
ORDER BY
  CASE EmployeeType
    WHEN 'Manager' THEN 0
    WHEN 'Memeber' THEN 1
    ELSE 2
  END, e.EmployeeID

或者您可以使用具有定义排序顺序的EmpType的表

CREATE TABLE EmpType(EmployeeType VARCHAR(20) PRIMARY KEY, SortOrder INT)
GO
INSERT INTO EmpType VALUES('Manager', 1)
INSERT INTO EmpType VALUES('Memeber', 2)

SELECT e.EmployeeType, e.EmployeeName AS [Team Member],    
  (SELECT e2.EmployeeName FROM Employee AS e2 WHERE e2.EmployeeID = e.ManagerID) AS Manager
FROM Employee AS e 
  LEFT OUTER JOIN EmpType as et
    ON e.EmployeeType = et.EmployeeType
ORDER BY et.SortOrder, e.EmployeeID

答案 1 :(得分:0)

没有“通用”解决方案。在您的示例中,不仅Employee类型而且Manager_id也可以更改。 如果您需要获得类似的结果,您应该订购层次结构级别。在这种情况下,首先是经理设置,然后是员工。如果员工有另一个managerId,它将保持在同一级别。