1. 程式人生 > >Sql 書寫技巧1

Sql 書寫技巧1

mysql的表在圖中。

資料庫中有一個表名為salesOrder的表

orderID(PK,合同ID)        region(地區)        sales(銷售人員)     total(合同金額)

1                                         A                            張三                          1000     

2                                         A                            李四                           5000

3                                         C                            趙五                          3000

4                                         A                             張三                          4000

5                                         C                            趙五                          2000

6                                         A                             張三                          3000

7                                         B                            王六                           5000

8                                         B                            錢七                           2500

9                                         B                            王六                           6000

一:統計出每個地區的合同金額合計並按此倒序排列顯示

  1. SELECT region ,sum(total) as rt FROM salesorder group by region order by rt desc ;
  2. 註釋:sum(total) as rt 的結果可以直接使用到 order by 中。

二:統計出每個地區的銷售人員數量

  1. select region,count(distinct(sales)) from salesorder groupby region;  
  2. 注意:去除重複的銷售人員

三:統計出每個地區合同金額最少的銷售人員

  1. SELECT t3.region, t3.sales, t3.st FROM ( region, sales, sum( total ) AS st FROM `salesorder` GROUP BY region, sales)t3, ( region, min( t.st ) AS st FROM ( region, sales, sum( total ) AS st FROM `salesorder` GROUP BY region, sales )t GROUP BY region)t2 WHERE t3.region = t2.region AND t3.st = t2.st
  2. 注意:先弄出 每個地區合同金額最少 的資料再與自身進行連線。
  3. 自身連線自身很重要

四:統計出所有超過本地區合同金額平均值的合同及金額

  1. selectdistinct q.* from (selectavg(total) as avgtotal,region  from salesorder groupby region) p,salesorder  
  2. where q.total>p.avgtotal;  
問題如下:
1、統計出每個地區的銷售人員數量
2、統計出每個地區合同金額最少的銷售人員
3、統計出所有超過本地區合同金額平均值的合同及金額
這號稱是一個面試題,是不是用到了儲存過程?
求高手幫忙解答

可以不用儲存過程
1, select region ,count(distinct(sales)) from SalesOrder group by region


2, select a.region,a.sales from SalesOrder a,(select region,min(total) total from SalesOrder group by region)b where a.total=b.total and a.region=b.region


3, select a.orderID,a.total from SalesOrder a,(select region,avg(total) total from SalesOrder group by region) b where a.region=b.region and a.total>b.total

1.每個地區的銷售總額並降序排列

2.每個地區的銷售人員數量

3.每個地區銷售金額最少的銷售人員

4.各個地區所有超過每個地區合同額的平均值的合同,銷售人員

select sum(total),region from a05 group by region order by 1 desc;

select count(*),region from a05 group by region;

select sale,region from (
select sale,region,row_number() over(partition by region order by total) rm from a05)
where rm=1;

select a05.region,total from a05,(select avg(total) avgtotal,region from a05 group by region) t
where a05.total > t.avgtotal
and a05.region = t.region;