如何在元组内排序(SQL)

时间:2011-10-27 12:58:21

标签: sql

我想得到一个表有两列和多行的答案。对于每一行,我希望以某种顺序显示两列,例如:

初始表:

+-----------+---------+
| nameA     | nameB   |
+-----------+---------+
| Ca        | Us      | 
| Db        | Ac      |  
+-----------+---------+

The target table is:

+-----------+---------+
| nameA     | nameB   |
+-----------+---------+
| Ca        | Us      | 
| Ac        | Db      |  
+-----------+---------+

如何解决?谢谢!

4 个答案:

答案 0 :(得分:2)

你可以尝试

SELECT
    (CASE WHEN nameA <= nameB THEN nameA
    ELSE nameB END) AS field1,
    (CASE WHEN nameA < nameB THEN nameB
    ELSE nameA END) AS field2
FROM your_table

答案 1 :(得分:1)

与Marco相似,但使用greatestleast函数:

SELECT
    least(nameA,nameB) AS field1,
    greatest(nameA,nameB) AS field2
FROM your_table

答案 2 :(得分:0)

如果我理解你的问题,那么以下更新应该交换名称B'低于'名称A的名称。

UPDATE table
SET nameA = nameB, nameB = nameA
WHERE nameB < nameA;

答案 3 :(得分:0)

SELECT nameA, nameB 
  FROM YourTable 
 WHERE nameA <= nameB 
UNION
SELECT nameB AS nameA, nameA AS nameB
  FROM YourTable 
 WHERE nameB < nameA;