输入表:
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
,依此类推。
答案 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