我有一个包含部门密钥(DEPA_KEY
)和房间密钥(OPRO_KEY
)的表。每个房间都在部门内,因此每个OPRO_KEY
都属于DEPA_KEY
。
我的问题是如何按名称对部门进行排序 - OPRO_NME
。如果我这样做:
SELECT * FROM @OPRO_ROOM
ORDER BY OPRO_NME
房间将在我不想要的部门之间混合。房间和部门必须保持在一起,这样每个人都可以很容易地看到哪个房间在哪个部门内。
这是表定义和插入:
DECLARE @OPRO_ROOM TABLE
(
DEPA_KEY INT,
OPRO_KEY INT,
OPRO_NME VARCHAR(255)
)
INSERT INTO @OPRO_ROOM(DEPA_KEY, OPRO_KEY, OPRO_NME)
VALUES(120000338,NULL,'B oddelek'),
(120000338,160000014,'Soba 1'),
(120000338,160000015,'Soba 2'),
(120000338,160000016,'Soba 3'),
(120000306,NULL,'C oddelek'),
(120000306,160000030,'Soba 1'),
(120000306,160000031,'Soba 3'),
(120000306,160000032,'Soba 7'),
(120000306,160000032,'Soba 7'),
(120000305,NULL,'A oddelek'),
(120000305,160000001,'Soba 1'),
(120000305,160000002,'Soba 3'),
(120000305,160000003,'Soba 4')
答案 0 :(得分:2)
我之前回答的更简单的内部联接版本:
select t.*
from @opro_room t
inner join @opro_room i
on i.depa_key = t.depa_key
and i.opro_key is null
order by i.opro_nme, t.opro_key
rextester演示:http://rextester.com/VWO57908
返回
+-----------+-----------+-----------+
| depa_key | opro_key | opro_nme |
+-----------+-----------+-----------+
| 120000305 | NULL | A oddelek |
| 120000305 | 160000001 | Soba 1 |
| 120000305 | 160000002 | Soba 3 |
| 120000305 | 160000003 | Soba 4 |
| 120000338 | NULL | B oddelek |
| 120000338 | 160000014 | Soba 1 |
| 120000338 | 160000015 | Soba 2 |
| 120000338 | 160000016 | Soba 3 |
| 120000306 | NULL | C oddelek |
| 120000306 | 160000030 | Soba 1 |
| 120000306 | 160000031 | Soba 3 |
| 120000306 | 160000032 | Soba 7 |
| 120000306 | 160000032 | Soba 7 |
+-----------+-----------+-----------+
答案 1 :(得分:1)
您只需要order by
中的两个键:
SELECT *
FROM @OPRO_ROOM
ORDER BY DEPA_KEY, OPRO_NME;
房间或部门是OPRO_NME
吗?我认为这是为部门。