Sql-Server

按兩列排序表

  • June 8, 2019

我想訂購這張桌子,但我找不到讓它工作的方法。你能幫助我嗎?

我有這張桌子:

桌子

我需要這個:

另一個

我有一個表格,其中列出了文件,第一個欄位是文件的 id,第二個欄位代表父親,所以我必須顯示一個列表,您可以在其中有序地看到 242 是第一個文件,252 和 335由 242 生成。

查詢:

select * from table_name order by col1 ASC, Col2 ASC

…對我不起作用。我做這個查詢:

SELECT
   FR1.[report_id],
   FR1.[report_parent] 
FROM [FARA_reports] FR1
WHERE
   FR1.[report_is_delete] <> 1 
   AND FR1.[report_is_tmp] <> 1
ORDER BY
   FR1.[report_id] asc, 
   FR1.[report_parent] desc

這是我的第一張照片。

另外一個選項:

select a, b
from t
order by 
   case when a < b or b is null then a else b end,
   case when a < b or b is null then b else a end ;

dbfiddle.uk中進行測試。

您的數據:

CREATE TABLE dbo.WEIRD_ORDERING
(
ID1 INT NULL,
ID2 INT NULL
);

INSERT INTO dbo.WEIRD_ORDERING VALUES
(242, NULL),
(243, NULL),
(244, NULL),
(252, 242),
(254, NULL),
(255, NULL),
(256, NULL),
(292, NULL),
(308, NULL),
(311, NULL),
(313, 311),
(314, 311),
(323, NULL),
(324, 311),
(335, 242),
(340, NULL),
(341, NULL),
(358, NULL),
(372, NULL),
(373, NULL),
(377, NULL),
(378, 358),
(379, 358),
(380, 358),
(381, 358);

這將為您提供所需順序的結果:

SELECT ID1, ID2
FROM
(
   SELECT ID1, ID2, ID1 AS ORDERING_COLUMN
   FROM dbo.WEIRD_ORDERING
   WHERE ID1 <= ID2 OR ID2 IS NULL

   UNION ALL

   SELECT ID1, ID2, ID2 AS ORDERING_COLUMN
   FROM dbo.WEIRD_ORDERING
   WHERE ID1 > ID2 OR ID1 IS NULL
) q
ORDER BY ORDERING_COLUMN, ID1;

分貝小提琴

引用自:https://dba.stackexchange.com/questions/234368