T-SQL:如何基于2列对表行进行排序

时间:2012-10-27 16:55:14

标签: tsql sorting rows multiple-columns

我现在已经坚持这个问题了。

如何根据B列的内容对A列进行排序?

我有这个样本:

ID  count   columnA     ColumnB
-----------------------------------
12  1      A         B
13  2      C         D
14  3      B         C

我想这样排序:

ID  count   ColumnA     ColumnB
-----------------------------------
12  1   A       B
14  3   B       C
13  2   C       D

所以如果上一行ColumnB =下一行ColumnA

,我需要对行进行排序

我在想一个循环?但无法想象它会如何运作......

我以为它会像这样(也许)

SELECT 
    a.ID, a.ColumnA, a.ColumnB
FROM 
    TableA WITH a (NOLOCK)
LEFT JOIN 
    TableA b WITH (NOLOCK) ON a.ID = b.ID AND a.counts = b.counts
WHERE
    a.columnB = b.ColumnA

上面的代码虽然不起作用,但我的想法更多......

DECLARE @counts int = 1
DECLARE @done int = 0

--WHILE @done = 0
BEGIN

SELECT 
    a.ID, a.ColumnA, a.ColumnB
FROM 
    TableA WITH a (NOLOCK)  
LEFT JOIN 
    TableA b WITH (NOLOCK)  ON a.ID = b.ID AND a.counts = @counts
WHERE 
    a.columnB = b.ColumnA

set @count = @count +1
END

如果这是一个C代码,对我来说会更容易,但是T-SQL的语法让像我这样的noobie变得有点困难。

非常感谢任何帮助!

编辑:示例代码

drop table tablea
create table TableA(
id int,
colA varchar(10),
colb varchar(10),
counts int
)

insert INTO TableA
(id, cola, colb, counts)
select 12, 'Bad', 'Cat', 3

insert INTO TableA
(id, cola, colb, counts)
select 13, 'Apple', 'Bad', 1

insert INTO TableA
(id, cola, colb, counts)
select 14, 'Cat', 'Dog', 2

select * FROM TableA

SELECT a.ID, a.ColA, a.ColB
FROM TableA a WITH (NOLOCK) 
LEFT JOIN TableA b WITH (NOLOCK) 
     ON a.ID = b.ID
Where a.colB = b.ColA
ORDER BY a.ColA ASC

1 个答案:

答案 0 :(得分:0)

您只需要添加ORDER BY子句

-- SELECT a.ID, a.ColumnA, a.ColumnB
-- FROM TableA WITH a (NOLOCK) 
--        LEFT JOIN TableA b WITH (NOLOCK) 
--            ON a.ID = b.ID
--               and a.counts = b.counts
-- Where a.columnB = b.ColumnA
ORDER BY a.ColumnA ASC