sql语句聚合等疑难问题收集

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

除法运算

select 500 / (501) *100

结果为0,由于数值是INT类型,怎么才能得到小数点呢?

select 500 / (501 + 0.0) *100

99.800300
这样就有小数点了。。。天那。。SQL真是有点笨。

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

获取当前日期 昨天日期

select getdate()-1 --2015-06-03 13:33:14.957
select DATEADD(DAY, -1, GETDATE()) --2015-06-03 13:33:14.957
select convert(varchar(10),getdate()-1,120) --2015-06-03

Year(getdate()) --当前年
Month(getdate()) --当前月
Day(getdate()) --当前日

Datediff(d,时间字段,getdate()) --得到离过生日还剩的天数

其它格式转换的范例如下:
--YYYY/MM/DD
Select Convert(varchar(10),Getdate(),111)
--YYYYMMDD
Select Convert(varchar(10),Getdate(),112)
--HH:MM:SS
Select Convert(varchar(8),Getdate(),108)
--HH:MM:SS:mmm
Select Convert(varchar(12),Getdate(),114)

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

数据表中比如有20条数据
读取前5条数据
select top 5 * from 表 order by id desc
读取前5条数据后的5条数据
(就是查询前10条记录,取后面5个)
select top 5 * from 表 where 
id not in (select top 5 id from 表)

===================================================================================
SELECT TOP 11 * FROM (

SELECT ROW_NUMBER() OVER (ORDER BY StuID) AS RowNumber, *
FROM StuInfo) t
WHERE RowNumber >= 10
假设StuID是StuInfo表的主键“学号”。先按学号排序,生成行号,再返回行号>=10时的前11条记录,即行号为10~20的11条记录。
=======================================================================
select top 10 * from [table_name] where id in (select top 20 id from [table_name] order by id desc) order by id asc
这样显示出来的就是:从11到20条数据
阿亮的笔记
原文地址:https://www.cnblogs.com/aiqingqing/p/4347062.html