Summary and Statistical Technique
上一篇 / 下一篇 2009-07-31 10:09:32 / 个人分类:SQL相关
本章节我们将会解决如下问题:
1.找出重复数据
2.找出the most common value
3.计算累计总值
4.为行编号
5.从一个表中选择top n行
在这个过程中,我们会学习很多关于Group By跟Having的知识。
How can I find authors with the same last name?
Select lastname, number_dups = count(*) from authors group by lastname having count(*)>1
【注1】 在select列表中的列必须是在group by中出现的,或是聚合函数,像count()等。
【注2】 count(*)等聚合函数作用于的是每一个分组中,而不一定是所有的行。
【注3】 在没有外连接等的情况下,count(*)比count(列名)效率快。
How can I find the value that occurs most frequently within a set of data?
Select total_sales, ccurs = count(*)
From titles
Group by total_sales
Having count(*) = max(count(*)) --这种方式在SQL Server好像不行,我换成了下面的方式
selecttop1 age,COUNT(*)
fromdbo.Employee
groupbyAge
orderbyCOUNT(*)desc
How can I create cumulative total?
id | sales |
1 | 20 |
2 | 10 |
3 | 50 |
4 | 22 |
5 | 32 |
6 | 48 |
7 | 12 |
Join the table to itself using ‘<=’join condition,group rows by key and datavalue and compute sum of data value within groups
selectx.id,total =SUM(y.sales) fromdbo.titles x,dbo.titles y wherey.id<=x.id groupbyx.id
How can I add row numbers to my result set?
以上表为例
本质上与上面的累计总和一样,不过就是把sum改成了count
selectx.id,line_no=COUNT(y.sales) fromdbo.titles x,dbo.titles y wherey.id<=x.id groupbyx.id
How can I flag non-contiguous data?
date 2009-07-27 20:24:00.000 2009-07-27 20:27:42.020 2009-07-27 20:29:42.023 2009-07-27 20:30:42.023 2009-07-27 20:31:42.027 2009-07-27 20:32:42.027
selectdatebefore=x.date,dateafter=MIN(y.date) fromdbo.sequentialData x,dbo.sequentialData y wherex.date<y.date groupbyx.date havingDATEDIFF(MI,MIN(y.date),x.date)<>-1 |
Ranking
要求从数据库选择前几行(Top n),这是一个经常性的问题,有几种方式可以解决这个问题:
1. 使用set rowcount n来限制查询返回的行数
2. 使用游标遍历结果集
3. 使用select top n
每种方式都有自己的优缺点,这需要根据实际情况来决定使用哪种方式
使用ROWCOUNT方式
显示按销量排列在前5的书
TAG:
清空Cookie -
联系我们 -
51Testing软件测试网 -
交流论坛 -
空间列表 -
站点存档 -
升级自己的空间
Powered by 51Testing
© 2003-2021
标题搜索
日历
«
2024-05-06
日
一
二
三
四
五
六
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 我的存档
数据统计
沪ICP备05003035号