t-sql单表查询基础

t-sql单表查询:

top:

select top n * from 表名 order by [列名]

  

distinct:

 select distinct [列名],[列名] from 表名

  

 where : 

条件运算法:

字母>数字

A=a&&a>0

字符串顺位比较

逻辑运算符:

not>and>or

NULL

任何值与NULl比较结果一定为UNKNOWN:       

NULL只与true/false做运算为true/false

列名<>'',已经刷选掉了NULL

order by

select [字段列表] from 表名 order by [ASC|DESC]

聚集函数:avg()、count()、max()、min()、sum()

null排序最小

  

group by

select sum(amout) sumamout,status from 表名 group by status 

可以把多行合并为一行

聚合结果增加条件,关键字为having

 

关键字执行顺序:

(1)FROM <table> 

(2)WHERE <where_condition> 

(3)GROUP BY <group_by_list> 

(4)HAVING <having_condition> 

(5)SELECT 

(6)DISTINCT 

(7)ORDER BY <order_by_list> 

(8)<TOP_specification> <select_list> 

  

行转列练习:

 
create table a(
 aid int,
 name varchar(10),
 score int
 );
 drop table a;
 select * from a;
 insert into a (aid,name,score)
 values(1,'aaa',90);
 insert into a (aid,name,score)
 values(1,'aab',91);
 insert into a (aid,name,score)
 values(2,'aaa',92);
 insert into a (aid,name,score)
 values(2,'aac',93);
 insert into a (aid,name,score)
 values(3,'aaa',90);
 --第一步
 select 
 aid,
 case name when 'aaa' then score else 0 end as aaa,
 case name when 'aab' then score else 0 end as aab,
 case name when 'aac' then score else 0 end as aac
 from a
 --第二步
 select 
 aid,
 sum(case name when 'aaa' then score else 0 end) as aaa,
 sum(case name when 'aab' then score else 0 end )as aab,
 sum(case name when 'aac' then score else 0 end )as aac
 from a
 group by aid

 

 

 

 

 

 

  
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值