我想在SQL中对每一行进行排序,示例如下

时间:2017-03-10 11:15:47

标签: mysql sql-server

输入表:

first           second        ID
vivek           singh         AB:CD
dheeraj         kumar         CD:AB
raj             sharma        AB:DF
neha            singh         DF:AB
shreya          shree         AB

输出表:

first           second        ID
vivek           singh         AB:CD
dheeraj         kumar         AB:CD
raj             sharma        AB:DF
neha            singh         AB:DF
shreya          shree         AB

我想对ID的值进行排序,但我希望将CD:AB视为等同于AB:CD,依此类推。

1 个答案:

答案 0 :(得分:0)

IF(并且它是一个很大的“如果”)你的id总是[two_letters]形式:[two_letters]或者只是[two_letters]然后这会起作用:

DECLARE @table TABLE (
    [first] VARCHAR(20),
    [second] VARCHAR(20),
    id VARCHAR(10));
INSERT INTO @table SELECT 'vivek', 'singh', 'AB:CD';
INSERT INTO @table SELECT 'dheeraj', 'kumar', 'CD:AB';
INSERT INTO @table SELECT 'raj', 'sharma', 'AB:DF';
INSERT INTO @table SELECT 'neha', 'singh', 'DF:AB';
INSERT INTO @table SELECT 'shreya', 'shree', 'AB';

--Input
SELECT * FROM @table;

--Output
WITH cte AS (
SELECT [first], [second], CASE WHEN id LIKE '%:%' THEN LEFT(id, 2) ELSE id END AS first_id, CASE WHEN id LIKE '%:%' THEN RIGHT(id, 2) END AS last_id FROM @table)
SELECT
    [first],
    [second],
    CASE
        WHEN first_id < last_id OR last_id IS NULL THEN first_id + ISNULL(':' + last_id, '')
        ELSE last_id + ISNULL(':' + first_id, '')
    END AS id
FROM
    cte;

给出以下结果:

first   second  id
vivek   singh   AB:CD
dheeraj kumar   AB:CD
raj     sharma  AB:DF
neha    singh   AB:DF
shreya  shree   AB