If tomorrow never comes

The meaning of life is creation,which is independent an boundless.

导航

Brusegao 实训笔记 T-SQL

Posted on 2008-11-27 17:22  Brucegao  阅读(267)  评论(0编辑  收藏  举报

1、从Northwind数据库中按升序排列查询第四个10ProductID的所有数据 

Use Northwind

select top 10 *

from Products

where ProductID>=

(select max(ProductID) from

(select top (30)ProductID from Products order by ProductID)as awqe)

查找Products表中20%数据

use Northwind

select top 20 percent*

from Products

 

2、给说查询的列取一个别名

use Northwind

select ProductID as y

from Products

 

设置多个查询列的别名:

select ProductID as x,ProductName as y

from Products

 

3、操作符 BETWEEN ... AND 会选取介于两个值之间的数据范围。这些值可以是数值、文本或者日期。

use Northwind

select ProductName

from Products

where ProductName between 'Chang' and 'Tofu'

 

如果想查询上面范围之外的数据如下:

use Northwind

select ProductName

from Products

where ProductName not between 'Chang' and 'Tofu'

4、查找Products表中ProductNameChangTofu的所有记录

use Northwind

select *

from Products

where ProductName in ('Chang','Tofu')

 

5%:匹配零个及多个任意字符; _:与任意单字符匹配; []:匹配一个范围; [^]:排除一个范围

use Northwind

select *

from Products

where ProductName like '%Ch%'

 

6、获取查询结果中不同的值

use Northwind

select distinct ProductID

from Products

 

7asc:sort ascending (升序)

   desc:sort descending(降序)

 

8count,avg,sum,max,min

use Northwind

select count(distinct ProductName)

from Products

select avg(UnitPrice) as '平均价格'

from Products

 

select min(UnitPrice) as '最低价格'

from Products

 

select max(UnitPrice) as '最高价格'

from Products

9Having是用来对函数产生的值设定条件的,而不能用Where,一个含有 HAVING 子句的 SQL

并不一定要包含 GROUP BY 子句。

select sum(UnitPrice) as '总价格'

from Products s

having sum(UnitPrice)>2000

 

 

 

 

而:

select sum(UnitPrice) as '总价格'

from Products

where sum(UnitPrice)>2000

是会报错的:

 

10、当我们选不只一个栏位,且其中至少一个栏位有包含函数的运用时,我们就需要用到

GROUP BY 这个指令。在这个情况下,我们需要确定我们有 GROUP BY 所有其他的栏位。换句话

说,除了有包括函数的栏位外,我 们都需要将其放在 GROUP BY 的子句中。

Use Northwind

select CategoryID,sum(UnitPrice)

from Products

group by CategoryID

 

11GROUP BY子句有个缺点,就是返回的结果集中只有合计数据,而没有原始的详细记录。如

果想在SQL SERVER中完成这项工作,可以使用COMPUTE BY子句。COMPTE生成合计作为附加的汇

总列出现在结果集的最后。当与BY一起使用时,COMPUTE 子句在结果集内生成控制中断和分类

汇总。

 

下列 SELECT 语句使用简单 COMPUTE 子句生成 titles 表中 price advance 的求和总计:

 

USE pubs

SELECT type, price, advance

FROM titles

ORDER BY type

COMPUTE SUM(price), SUM(advance)

 

 

下列查询在 COMPUTE 子句中加入可选的 BY 关键字,以生成每个组的小计:

 

USE pubs

SELECT type, price, advance

FROM titles

ORDER BY type

COMPUTE SUM(price), SUM(advance) BY type

SELECT 语句的结果用12 个结果集返回,六个组中的每个组都有两个结果集。每个组的第一

个结果集是一个行集,其中包含选择列表中所请求的信息。每个组的第二个结果集包含

COMPUTE 子句中两个 SUM 函数的小计。