让UNION与ORDER BY并存于SQL语句当中
http://www.cnblogs.com/yinzhenzhixin/archive/2009/01/07/1371064.html
在SQL语句中,UNION关键字多用来将并列的多组查询结果(表)合并成一个结果(表),简单实例如下:
SELECT [Id],[Name],[Comment] from [Product1]
UNION
SELECT [Id],[Name],[Comment] from [Product2]
上面的代码可以实现将从Product1和Product2两张表合并成一个表,如果您只是希望合并两张表中符合特定条件的记录抑或是合并两张表各自的前N条记录,那么您的代码可能会像下面这样写:
SELECT [Id],[Name],[Comment] from [Product1] WHERE LEN([Name]) > 5
UNION
SELECT [Id],[Name],[Comment] from [Product2] WHERE [Id] IN (11,20) AND [Comment] IS NOT NULL
SELECT TOP N [Id],[Name],[Comment] from [Product1]
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product2]
This is so easy!但是假如您希望从包含Type字段的某表中根据Type分别随机筛选N条记录并将结果合并成一张表,您可能会像下面这样写:
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE1' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE2' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE3' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE4' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE5' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE6' ORDER BY NEWID()
UNION
SELECT TOP N [Id],[Name],[Comment] from [Product] WHERE [Type]='TYPE7' ORDER BY NEW
相关文档:
Cross Apply使表可以和表值函数结果进行join, 这样表值函数的参数就可以使用一个结果集,而不是一个标量值,下面是book online的原文,有例子,有解释。
The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query. The table-valued function act ......
I'm continually trying to track down what service packs are installed on various SQL Servers I support. I can never find the right support page on Microsoft's site. So here's an article with all the SQL Server version information I can track down. If you know of any older versions or can help me fil ......
应一个朋友的要求,贴上收藏的SQL常用分页的办法~~
表中主键必须为标识列,[ID] int IDENTITY (1,1)
1.分页方案一:(利用Not In和SELECT TOP分页)
语句形式:
SELECT TOP 页记录数量 *
from 表名
WHERE (ID NOT IN
(SELECT TOP (每页行数*(页数-1)) ID
from 表名
ORDER BY ......
Suppose we have a recursive hierarchy stored in a relational database and we want to write it to XML. This might be for a variety of reasons – e.g. as a pre-cached input to a UI control, to export to another system using a pre-defined format, etc.
In SQL Server 2000, in order to ......
一:Select语句:
select 字段名 from 表名 where 条件 order by 排序
see:select distinct 从多个相同字段中抓唯一值
see:查找ld_det_andy表中有数据但ld_det_temp表中没数据的数据
select * from ld_det_a ......