Summary and Statistical Technique

上一篇 / 下一篇  2009-07-31 10:09:32 / 个人分类:SQL相关

本章节我们将会解决如下问题:

      1.找出重复数据

      2.找出the most common value

      3.计算累计总值

      4.为行编号

      5.从一个表中选择top n

在这个过程中,我们会学习很多关于Group ByHaving的知识。

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:25: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:

 

评分:0

我来说两句