`
虚弱的java
  • 浏览: 160185 次
  • 性别: Icon_minigender_1
  • 来自: 哈尔滨
社区版块
存档分类
最新评论

Sql2008--5

Go 
阅读更多

--函数
--1、使用在select语句的查询选择列表中,以返回一个值
--select COUNT();---返回记录行数
--2、使用where子句搜索条件中,用来限制符合查询条件的行
use school
go
select [id],name
from student
where student.ID=(select MAX([id]) from student)--获取最大值

--3、使用视图的搜索条件(where子句)中,以使视图在运行时与用户动态地保持一致
create view studentinfo as
select [id],name
from student
go

--4、使用在CHECK约束或触发器中,以在插入数据时查找指定的值
create table SalesContacts
(SalesRepID int primary key check (SalesRepID = SUSER_SID()),
ContactName varchar(50) null,
ContactPhone varchar(13) null);
go
--使用在DEFAULT约束或触发器中,以在INSERT语句未指定值的情况下提供一个值
CREATE table SalesContacts
(
SalesRepID int primary key check(SalesRepID = SUSER_SID()),
ContactName varchar(30) null,
ContactPhone varchar(10) null,
WhenCreated DATETIME DEFAULT GETDATE(),
Creator INT DEFAULT SUSER_SID()
)


--ALL:对所有的值进行聚合函数查询
--DISTINCT:指定AVG只在每个值的唯一实例上执行,不管该值出现几次

use AdventureWorks
go
select AVG(vacationHours) as '平均小时',
sum(SickLeaveHours) as '小时总数'
from humanresources.employee
where title like 'Vice President%'

--MIN()函数用来求最低值,或者最小值
use AdventureWorks
go
SELECT MIN(TaxRate)
from Sales.SalesTaxRate;
go
--MAX()求最大值
use AdventureWorks
go
select MAX(a.TaxRate)
from Sales.SalesTaxRate a;
go
--SUM函数求总和
use AdventureWorks
go
select a.Color,SUM(a.ListPrice),SUM(a.StandardCost)
from Production.Product a
where a.Color is not null
and a.ListPrice !=0.0
and a.Name like 'Mountain%'
group by a.Color   --使用Color列来对结果集分组
order by Color; --使用Color列来对结果集排序
go
--使用COUNT和COUNT_BIG函数求行总数,COUNT返回int类型,COUNT_BIG返回bigint类型
use AdventureWorks
go
select COUNT(distinct title)
from HumanResources.Employee;
go

use AdventureWorks
go
select COUNT(*)
from HumanResources.Employee;
go

use AdventureWorks
go
select COUNT(*),AVG(Bonus)
from Sales.SalesPerson
where SalesQuota > 25000;
go

--DATEDIFF()函数获取日期和日间差值,用来获取两个日期的差或两个时间的差,返回值为int类型
--DATEDIFF(datepart,startdate,enddate)
--datepart:是指定所跨边界类型的startdate和enddate的一部分,参数值是指定的内容
--ISDATE()函数 可以判断给定的表达式是否为日期类型
--
select ISDATE(DATEADD(year,1000,getdate()))
select ISDATE('2007-03-15T08:55:00.000');

--使用CAST和CONVERT函数转换数据类型
use AdventureWorks
go
select SUBSTRING(Name,1,30) as ProductName,ListPrice
from Production.Product p
where CAST(ListPrice as int) like '4%'
go
--使用CONVERT函数
use AdventureWorks
go
select SUBSTRING(name,1,30) as ProductName,ListPrice
from Production.Product
where CONVERT(int,ListPrice) like '4%'
go
--使用IDENITY函数生成一个自增列
select identity(int,1,1) as id_num
into NEWTABLE
from OldTable

select id_num=IDENTITY(int,1,1)
into newtable
from oldtable;

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics