必須會的SQL語句(六) 數(shù)據(jù)查詢
1.基礎(chǔ)的查詢
1)重命名列
select name as '姓名' from 表名
2)定義常量列
select 是否 ='是' from 表名
3)top用法 percent
--這種寫法可以獲取前20%條字段。
select top 20 percent * from 表名
4)去除重復(fù)列
select distinct 列名 from 表名
5)聚合函數(shù)
max avg count min sum
--多個(gè)聚合結(jié)果 在一個(gè)結(jié)果集中
select
最大年齡 = (select max(age) from 表名),
最小年齡 = (select min(age) from 表名)
6)between and
select * from 表 where xx between 5 and 6
2.Union 使用Union將兩個(gè)結(jié)果集匯聚在一起。
-- 年齡 工資
-- ————————
-- 19 $20000
-- 50 $20005
-- 30 $23000
-- 匯總 $63005
-- 查詢各年齡段工資,同時(shí)顯示所有工資匯總。(像上邊的表)
select
--把年齡轉(zhuǎn)換成varchar類型
Convert(varchar(10),[age]) as 年齡
Sum([salary]) as 工資
from 員工表
group by age
--將兩個(gè)結(jié)果集,合并成一個(gè)結(jié)果集
union
select
--匯總是一個(gè)常量列
'匯總' , sum(salary)
from 員工表
使用union合并兩個(gè)結(jié)果集時(shí),
兩個(gè)結(jié)果集列數(shù)必須一致,并且數(shù)據(jù)類型對應(yīng)。
這就是代碼中,把年齡轉(zhuǎn)換成varchar的原因。
3.Order by
-- Order by 用于結(jié)果集排序,
-- 其Order他后邊不只可以接一個(gè)字段,
-- 也能接一個(gè) 表達(dá)式。
Select *
from 表
order by (age+salary)/2.0 desc
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。