一些简单的sq例子

来源:互联网 发布:轮胎数据怎么看 编辑:程序博客网 时间:2024/05/01 11:20

1、根据分数算等级 <60不及格,>=60及格,>85 优秀

Math

id     score  

1        45 

6        60 
8        51 
9        98 

sql:

select *,'range'= case  
when score<60 then '不及格' 
when score>=60 then '及格' 
when score>85 then '优秀' 
end 
from math

结果:

Math

id     score    range

1        45        不及格

6        60        及格
8        51        不及格
9        98         优秀

-----------------------------------------------------------------------------------------------------------------------------------

2、having的用法,用于在group by 后边条件

文章                                      |                 评论                               |              

article                                    |              comment                        |             User

ID  userID                            |               ID      userID                   |                 ID

1    3                                      |               1          5                          |                   1

2    3                                      |               2          3                          |                   2

3    5                                      |               3          2                          |                   3

4    3                                      |               4          1                          |                   4

5    2                                      |               5           5                         |                   5

                                              |                6            7                        |                    7

sql:

select a.id,count(b.id) 'commtnum' from [user]  a join comment b on a.id=b.userid group by a.id having count(b.id)>1

结果:

id  commtnum

5      2

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

3、用于分页的sql

with tt as (select *,row_number() over(order by id) num from 
math) 

select * from tt where num between 3 and 6

结果:

id   score   userid  num

3        51         1         3
4        98         9         4

4、取每个人的第一条评论

select * from (select *,row_number() over(partition by userid order by id) rows from 
comment ) ggg where rows=1

结果:

id   userid  rows

4         1         1
3         2         1
2         3         1
1         5         1
6         7         1