按列排序

时间:2019-04-14 07:30:39

标签: sorting sql-server-2008 sql-order-by columnsorting

我有两个表,PRODUCTS和LOOKUP TABLES。现在,我想根据LOOKUP TABLE中的KEY列值来订购产品表中的KEY列。

CREATE TABLE PRODUCTS
(
    ID INT,
    KEY VARCHAR(50)
)

INSERT INTO PRODUCTS 
VALUES (1, 'EGHS'), (2, 'PFE'), (3, 'EGHS'),
       (4, 'PFE'), (5, 'ABC')

CREATE TABLE LOOKUP (F_KEY VARCHAR(50))

INSERT INTO LOOKUP VALUES('PFE,EGHS,ABC')

现在,我想根据LOOKUP表中的KEY(PFE,EGHS,ABC)值对PRODUCTS表中的记录进行排序。

示例输出:

产品

ID   F_KEY
-----------    
2    PFE
4    PFE
1    EGHS
3    EGHS
5    ABC

我使用此查询,但它不起作用

SELECT * 
FROM PRODUCTS 
ORDER BY (SELECT F_KEY FROM LOOKUP)

2 个答案:

答案 0 :(得分:1)

您可以使用XML分割字符串。您首先需要将字符串转换为XML,并用开始和结束XML标记替换逗号。

完成后,您可以使用ROW_NUMBER()分配一个递增数字,如下所示。

;WITH cte 
     AS (SELECT dt, 
                Row_number() 
                  OVER( 
                    ORDER BY (SELECT 1)) RN 
         FROM   (SELECT Cast('<X>' + Replace(F.f_key, ',', '</X><X>') 
                             + '</X>' AS XML) AS xmlfilter 
                 FROM   [lookup] F)F1 
                CROSS apply (SELECT fdata.d.value('.', 'varchar(500)') AS DT 
                             FROM   f1.xmlfilter.nodes('X') AS fdata(d)) O) 
SELECT P.* 
FROM   products P 
       LEFT JOIN cte C 
              ON C.dt = P.[key] 
ORDER  BY C.rn 

Online Demo

输出:

ID   F_KEY
-----------    
2    PFE
4    PFE
1    EGHS
3    EGHS
5    ABC

答案 1 :(得分:1)

您可以这样做:

SELECT ID, [KEY] FROM PRODUCTS
ORDER BY
CASE [KEY]
  WHEN 'PFE' THEN 1
  WHEN 'EGHS' THEN 2
  WHEN 'ABC' THEN 3
END