易截截图软件、单文件、免安装、纯绿色、仅160KB

让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


相关文档:

介绍SQL Server 2005的CROSS Apply

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 ......

5本经典SQL电子书


SQL宝典

SQL必知必会第三版

SQL入门经典第四版

Sams Teach Yourself SQL in 10 Minutes Third Edition

SQL The Complete Reference

......

SQL Server 得到行号的SQL

SQL Server 得到行号的SQL
使用临时表:
select   id=identity(int,1,1),value   into   #temp   from   YourTable  
  select   *   from   #temp  
  drop   table   #temp  
取得第11到20行记录:
select   IDENTITY(in ......

SQL知识整理

一:Select语句:
       select 字段名 from 表名 where 条件 order by 排序
see:select distinct 从多个相同字段中抓唯一值    
see:查找ld_det_andy表中有数据但ld_det_temp表中没数据的数据
        select * from ld_det_a ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号