如何按列按另一列的顺序排序

时间:2015-06-29 07:47:31

标签: sql sql-server sql-server-2008

我有这个查询给了我这张表:

SELECT 
CS.Name, 
CS.FirstStep,
--CSS.NextCAPAStepID,
CS.ID
FROM CAPA_STEP_SEQUENCE CSS
LEFT JOIN CAPA_STEP CS ON CS.ID = CSS.CAPAStepID
WHERE CAPAStepID in (100000009,100000010,100000011,100000012,100000013)
GROUP BY CS.Name, CS.ID, CS.FirstStep
ORDER BY CS.FirstStep DESC

http://postimg.org/image/68jxjuorp/

我必须通过此列从另一个表中对此表进行排序:

SELECT NextCAPAStepID
FROM CAPA_STEP_SEQUENCE 
WHERE CAPAStepID in (100000009,100000010,100000011,100000012,100000013)

http://postimg.org/image/ykxse0025/

当我尝试通过CSS.NexstCAPAStepID的第一个查询进行排序时,它使得在第一个顺序列中NextCAPAStepID被排序为ASC然后整个表按此顺序排序但在我的情况下我想按顺序从CSS排序整个表.NextCAPAStepID。另请注意,FirstStep列中值为1的行应始终位于顶部。

最终结果应如下所示:http://pho.to/9XC6P

表格的脚本:

-- Create Table
CREATE TABLE FirstTable (ID INT, Name VARCHAR(100), FirstStep INT)
-- Insert Data
INSERT INTO FirstTable VALUES (100000009,'Step', 1);
INSERT INTO FirstTable VALUES (100000010,'Step 1', 0);
INSERT INTO FirstTable VALUES (100000011,'Step 2', 0);
INSERT INTO FirstTable VALUES (100000012,'Step 3', 0);
INSERT INTO FirstTable VALUES (100000013,'Step 4', 0);
-- Create Table
CREATE TABLE SecondTable (NextCAPAStepID INT)

-- Insert Data
INSERT INTO SecondTable VALUES (100000011);
INSERT INTO SecondTable VALUES (100000012);
INSERT INTO SecondTable VALUES (100000010);
INSERT INTO SecondTable VALUES (100000013);
INSERT INTO SecondTable VALUES (NULL);

1 个答案:

答案 0 :(得分:0)

这只是猜测,但我认为你想要这样的东西:

;WITH cte AS(SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn 
             FROM dbo.SecondTable)
SELECT ft.* FROM FirstTable ft
LEFT JOIN cte c ON ft.id = c.NextCAPAStepID
ORDER BY ft.FirstStep DESC, CASE WHEN c.rn IS NULL THEN 2 ELSE 1 END, c.rn

输出:

ID          Name    FirstStep
100000009   Step    1
100000011   Step 2  0
100000010   Step 1  0
100000012   Step 3  0
100000013   Step 4  0

即。按第二个表中的可见顺序在第一个表中订购数据,但除非您没有严格的订购,否则将无法保证。您最好在第二个表中添加一些排序列并按该列排序...