SQL Server中ORDER BY後面能夠是表達式和子查詢

假如SQL Server數據庫中如今有Book表以下數據庫

CREATE TABLE [dbo].[Book]( [ID] [int] IDENTITY(1,1) NOT NULL, [BookName] [nvarchar](50) NULL, [BookDescription] [nvarchar](50) NULL, [ISBN] [nvarchar](20) NULL, [CreateTime] [datetime] NULL, CONSTRAINT [PK_Book] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Book] ADD  CONSTRAINT [DF_Book_CreateTime]  DEFAULT (getdate()) FOR [CreateTime]

有以下數據:express

SET IDENTITY_INSERT [dbo].[Book] ON 
GO
INSERT [dbo].[Book] ([ID], [BookName], [BookDescription], [ISBN], [CreateTime]) VALUES (1, N'Chinese', N'This is a very good Chinese book', N'0001', CAST(N'2018-10-17T15:25:18.450' AS DateTime)) GO
INSERT [dbo].[Book] ([ID], [BookName], [BookDescription], [ISBN], [CreateTime]) VALUES (2, N'English', N'English', N'0002', CAST(N'2018-10-17T15:25:18.457' AS DateTime)) GO
INSERT [dbo].[Book] ([ID], [BookName], [BookDescription], [ISBN], [CreateTime]) VALUES (3, N'Japanese', N'Japanese', N'0003', CAST(N'2018-10-17T15:25:18.473' AS DateTime)) GO
INSERT [dbo].[Book] ([ID], [BookName], [BookDescription], [ISBN], [CreateTime]) VALUES (4, N'Russian', N'Russian', N'0004', CAST(N'2018-10-17T15:25:18.483' AS DateTime)) GO
INSERT [dbo].[Book] ([ID], [BookName], [BookDescription], [ISBN], [CreateTime]) VALUES (5, N'Italian', N'Italian', N'0005', CAST(N'2018-10-17T15:25:18.493' AS DateTime)) GO
SET IDENTITY_INSERT [dbo].[Book] OFF

 

咱們使用SELECT語句查詢該表,以下所示:spa

SELECT *
FROM [dbo].[Book]

 

如今設想一個問題,咱們如何根據[BookName]和[BookDescription]兩列數據的聯合值來對結果進行排序呢?3d

我想不少人都會想到用子查詢,以下所示:code

SELECT [ID],[BookName],[BookDescription],[ISBN],[CreateTime]
FROM ( SELECT [ID],[BookName],[BookDescription],[ISBN],[CreateTime],[BookName]+N'#'+[BookDescription] AS [Combine]
    FROM [dbo].[Book] ) AS T ORDER BY [Combine]

 

像上面這樣用子查詢的確沒有問題,可是你知道嗎,咱們是能夠直接在ORDER BY語句中寫表達式的,以下所示:blog

SELECT *
FROM [dbo].[Book]
ORDER BY [BookName]+N'#'+[BookDescription]

結果和用子查詢徹底同樣排序

 

咱們也能夠在ORDER BY中使用多個表達式和列來對結果進行排序,甚至咱們能夠根據一個子查詢來對結果進行排序,以下所示:ip

SELECT *
FROM [dbo].[Book]
ORDER BY [BookName]+N'#'+[BookDescription] ASC, (SELECT TOP 1 R_BOOK.[ISBN] FROM [dbo].[Book] AS R_BOOK WHERE R_BOOK.[BookName]=[BookName]) DESC, --這裏的子查詢只能返回一行和一列數據,不然SQL Server會報錯
         [CreateTime] ASC

 

可是ORDER BY後面不能是常量,好比下面這樣咱們在ORDER BY後面跟一個字符串常量是不行的:字符串

SELECT *
FROM [dbo].[Book]
ORDER BY N'Constant'

執行該語句會報錯:get

Msg 408, Level 16, State 1, Line 3 A constant expression was encountered in the ORDER BY list, position 1.
相關文章
相關標籤/搜索