易截截图软件、单文件、免安装、纯绿色、仅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 ......

SQL Server 的连接、查询与更新

#Region " 命名空间 "
Imports System.Data
Imports System.Data.SqlClient
#End Region
Public Class DBCommon
Implements IDisposable
#Region " 成员变量 "
Private conn As SqlConnection
Private cmd As SqlCommand
Private trans As SqlTransaction
#End Region
#Region " 构造函数 "
......

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

sql各种语句的完整语法

下列语句部分是Mssql语句,不可以在access中使用。
SQL分类:
DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE)
DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)
DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)
首先,简要介绍基础语句:
1、说明:创建数据库
CREATE DATABASE database-nam ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号