假设我有一个包含偶数行的表。例如,一个表有两列Name和EmpCode的Employee表。该表看起来像
Name EmpCode
Ajay 7
Vikash 5
Shalu 4
Hari 8
Anu 1
Puja 9
现在,我希望我的输出与EmpCode相反,如:
Name EmpCode
Ajay 9
Vikash 1
Shalu 8
Hari 4
Anu 5
Puja 7
我需要在SQL Server中运行此查询。
答案 0 :(得分:3)
由于OP没有回复,我将为他们发布一些解释。正如大家所想的那样,SQL Server中的表没有内置的排序。您的数据存储在所谓的HEAP中。这意味着,当您在没有ORDER BY
的情况下运行查询时,您的数据可以返回服务器感觉的任何顺序。对于小数据集,此可能按照您插入的顺序排列,但就是这样(可能)。
当您进入较大的数据集时,并且当您在操作上运行多个核心时,SELECT * FROM [Table];
的顺序更可能不是插入的顺序,并且更可能是随机的每个运行查询的实例。我有几个表,其中SELECT TOP 1 *...
将在运行查询时返回不同的行每时间;即使使用CLUSTERED INDEX
。
保证订单的唯一,是唯一方式是使用ORDER BY
。现在,您可能有另一个您尚未共享的列,您可以订购,但如果没有,也许这个(非常)简单的示例至少会帮助您,如果没有其他的话:
CREATE TABLE #Employee ([Name] varchar(10), EmpCode tinyint);
INSERT INTO #Employee
VALUES ('Ajay',7),
('Vikash',5),
('Shalu',4),
('Hari',8),
('Anu',1),
('Puja',9);
GO
--Just SELECT *. ORDER is NOT guaranteed, but, due to the low volume of data, will probably be in the order by insertion
SELECT *
FROM #Employee;
--But, we want to reverse the order, so, let's add an ORDER BY
SELECT *
FROM #Employee
ORDER BY [Name];
--Oh! That didn't work (duh). Let's try again
SELECT *
FROM #Employee
ORDER BY Empcode;
--Nope, this isn't working. That's because your data has nothing related to it's insertion order. So, let's give it one:
GO
DROP TABLE #Employee;
CREATE TABLE #Employee (ID int IDENTITY(1,1), --Oooo, what is this?
[Name] varchar(10),
EmpCode tinyint);
INSERT INTO #Employee
VALUES ('Ajay',7),
('Vikash',5),
('Shalu',4),
('Hari',8),
('Anu',1),
('Puja',9);
GO
--Now look
SELECT *
FROM #Employee;
--So, we can use an ORDER BY, and get the correct order too
SELECT [Name],
Empcode
FROM #Employee
ORDER BY ID;
--So, we got the right ORDER using an ORDER BY. Now we can do something about the ordering:
--We'll need a CTE for this:
WITH RNs AS(
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID ASC) AS RN1,
ROW_NUMBER() OVER (ORDER BY ID DESC) AS RN2
FROM #Employee)
SELECT R1.[Name],
R2.EmpCode
FROM RNs R1
JOIN RNs R2 ON R1.RN1 = R2.RN2;
GO
DROP TABLE #Employee;