0

我现在很困扰这个问题一段时间..

如何根据 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 的语法对于像我这样的菜鸟来说有点困难。

任何帮助是极大的赞赏!

编辑:示例代码

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
4

1 回答 1

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
于 2012-10-27T16:57:26.650 回答