SQL Server代码段

1.cast和convert

 1 select CAST('123' as int)   -- 123 
 2 select CONVERT(int, '123')  -- 123 
 3  
 4  
 5 select CAST(123.4 as int)   -- 123 
 6 select CONVERT(int, 123.4)  -- 123  
 7  
 8  
 9 select CAST('123.4' as int) 
10 select CONVERT(int, '123.4') 
11 -- Conversion failed when converting the varchar value '123.4' to data type int. 
12  
13  
14 select CAST('123.4' as decimal)  -- 123 
15 select CONVERT(decimal, '123.4') -- 123  
16  
17  
18 select CAST('123.4' as decimal(9,2))  -- 123.40 
19 select CONVERT(decimal(9,2), '123.4') -- 123.40 
20  
21  
22 declare @Num money 
23 set @Num = 1234.56 
24 select CONVERT(varchar(20), @Num, 0)  -- 1234.56 
25 select CONVERT(varchar(20), @Num, 1)  -- 1,234.56 
26 select CONVERT(varchar(20), @Num, 2)  -- 1234.5600

 

 

2.Distinct去重

在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。

表A:

表B:

1.作用于单列

1 select distinct name from A

执行后结果如下:

2.作用于多列

示例2.1

1 select distinct name, id from A

执行后结果如下:

实际上是根据name和id两个字段来去重的,这种方式Access和SQL Server同时支持。

示例2.2

1 select distinct xing, ming from B

返回如下结果:

返回的结果为两行,这说明distinct并非是对xing和ming两列“字符串拼接”后再去重的,而是分别作用于了xing和ming列。

3.COUNT统计

1 select count(distinct name) from A;      --表中name去重后的数目, SQL Server支持,而Access不支持

count是不能统计多个字段的,下面的SQL在SQL Server和Access中都无法运行。

1 select count(distinct name, id) from A;

若想使用,请使用嵌套查询,如下:

1 select count(*) from (select distinct xing, name from B) AS M;

4.distinct必须放在开头

1 select id, distinct name from A;   --会提示错误,因为distinct必须放在开头

5.其他

distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。但可以通过其他方法实现关于SQL Server将一列的多行内容拼接成一行的问题讨论

 

参考:

http://www.cnblogs.com/rainman/archive/2013/05/03/3058451.html#m1

 

posted @ 2017-07-31 11:14  imstrive  阅读(688)  评论(0编辑  收藏  举报