0

我有一个表 EMPLOYEE 定义如下:

CREATE TABLE EMPLOYEE
(
  Employee varchar(50),
  Manager varchar(50),
  field1 bit,
  field2 bit 
) 
INSERT INTO EMPLOYEE VALUES ('Emp1','Mgr1',1,0)
INSERT INTO EMPLOYEE VALUES ('Contactor1','',0,0)
INSERT INTO EMPLOYEE VALUES ('Mgr1','',0,1)
INSERT INTO EMPLOYEE VALUES ('Mgr2','',0,1)
INSERT INTO EMPLOYEE VALUES ('Emp2','Mgr2',1,0)
INSERT INTO EMPLOYEE VALUES ('Emp3','Mgr2',1,0)
INSERT INTO EMPLOYEE VALUES ('Contractor2','',0,0)
INSERT INTO EMPLOYEE VALUES ('Emp4','Mgr1',1,0)

假设:

  1. 如果 field1 等于 1,则实体是员工。

  2. 如果 field2 等于 1,则实体是经理。

  3. 如果 field1 和 field2 等于 0,则实体是承包商。

  4. 特定行的 field1 和 field2 的值不能为 1。

查询 SELECT * FROM EMPLOYEE 返回以下值:

在此处输入图像描述

我需要一个查询,以便我可以得到以下格式的结果:

期望的输出

基本上,结果应该是第一个经理,然后是相应的员工,下一个经理,然后是相应的员工,最后应该是所有承包商。

4

2 回答 2

1

仅根据您的示例数据和预期结果,这有效:

select * from Employee order by
CASE WHEN Employee like 'C%' THEN 1 ELSE 0 END, --Force Contractors to the end
COALESCE(NULLIF(Manager,''),Employee), --Get employees and their managers together
CASE WHEN Employee like 'M%' THEN 0 ELSE 1 END, --Sort Managers before employees
Employee --Sort by employee name

但是,如果您有更复杂的数据,请在我的评论中注意我的问题

并如修正问题中所定义field1field2

select * from Employee order by
CASE WHEN field1=0 and field2=0 THEN 1 ELSE 0 END, --Force Contractors to the end
COALESCE(NULLIF(Manager,''),Employee), --Get employees and their managers together
field2 desc, --Sort Managers before employees
Employee --Sort by employee name
于 2013-05-17T08:32:50.500 回答
1

基本顺序是

... ORDER BY Manager + Employee

如果 Manager 允许 NULL,IMO 更好

... ORDER BY ISNULL(Manager, Employee)

对于 SQL Server 2012,无论是否为 NULL

... ORDER BY CONCAT(Manager,Employee)

但是,没有区分器来显示员工、承包商和经理的差异

所以使用实际的字符串值......

ORDER BY
    CASE WHEN Employee LIKE 'Contractor%' THEN 1 ELSE 0 END,
    CONCAT(Manager,Employee)
于 2013-05-17T08:33:21.723 回答