總網頁瀏覽量

2013年1月22日 星期二

SQL函數

本文章主要是MSSQL的函數
有些函數mysql裡面沒有
例如:NEWID()

SQL函數通常與select配合使用
官網部分將函數分成許多類別:
字串函數、時間函數、彙總函數


1.資料型態轉換:
convert(型態,欄位)
例如:select CONVERT(char(10),height) as total,* from student where height > 180 //int 轉成char

2.列出現在的年月日時分秒
語法:select/print GETDATE()
結果:01 23 2013 12:17AM
語法:select/print CONVERT(varchar(20),getdate())
結果:01 23 2013 12:17AM
語法:select/print CONVERT(varchar(20),getdate(),101)
結果:01/23/2013
語法:select/print CONVERT(varchar(20),getdate(),102)
結果:2013.01.23
語法:select/print CONVERT(varchar(20),getdate(),120)
結果:2013-01-23 00:17:06
3.
substring

4.
index

5.計算(符合某條件下的)紀錄筆數:count(欄位)
select count(employeeid) from table_name (where .....);
但是不會將null值算進去
如果要將null值也算進去則
select count(*) from table_name;

6.列出欄位的值域:distinct
例如:想看員工來自哪些國家
select distinct (country) from Employees;

7.隨機挑選n筆資料 :select top n ... from ... [where...] order by NEWID()
例如:從order details隨機挑選六筆資料
select top 6   * from [Order Details]  order by NEWID()
例如:樂透開獎機
select top 6 * from products where productid < 49 order by NEWID()
productid 最好是主鍵,否則會重複開獎

查詢結果會發現資料並非以任何欄位的順序排列。
那是因為NEWID()函數會產生uniqueidentifier型態的唯一資料,這種資料稱之為全域唯一識別碼(GUID),長度為十六位元組(16 bytes,32 bits)的二進位值,長相如:34D92DC7-7BEB-4825-8DF1-004B40F602C8,
因此select結果是以GUID排列。


每台電腦也有GUID值,全世界的電腦都不會產生重複的GUID

8.彙總函數
選定特定欄位,進行運算得出統計結果
max(欄位)、min(欄位)、sum(欄位)、avg(欄位)、算標準差的stdev(欄位)、算變異數的var(欄位)

沒有留言:

張貼留言