sql 選取分組中的第一條,顯示聚合之外的列,having字句的使用

分組中的第一條:
select * from
(
select row_number() over(partition by 列1,列2,... order by 列1,列2,...) as rownum -- 排序並分組
, * -- 所需顯示的字段
from 表
) as T
where T.rownum = 1

顯示聚合之外的列:
SELECT   a.examroomnum ,
          a.positionnum ,
          a.人數 ,
          a.suminterviewscore ,
          a.avginterviewscore ,
          b.Department
  FROM     SELECT     examroomnum ,
                      positionnum ,
                      COUNT (*)  AS  人數 ,
                      SUM (interviewscore) suminterviewscore ,
                      AVG (interviewscore) avginterviewscore
            FROM       examinee
            GROUP  BY   examroomnum ,
                      positionnum
          ) a
          LEFT  JOIN  examinee b  ON  a.examroomnum = b.examroomnum
                                  AND  a.positionnum = b.positionnum
 
having字句的使用:

HAVING語句一般與GROUP BY語句聯合使用,用來過濾由GROUP BY語句返回的記錄集。sql

HAVING語句的存在彌補了WHERE關鍵字不能與聚合函數聯合使用的不足。express

語法:函數

SELECT column1, column2, ... column_n, aggregate_function (expression)FROM tablesWHERE predicatesGROUP BY column1, column2, ... column_nHAVING condition1 ... condition_n;spa

一樣使用本文中的學生表格,若是想查詢平均分高於80分的學生記錄能夠這樣寫:code

SELECT id, COUNT(course) as numcourse, AVG(score) as avgscore排序

FROM studentget

GROUP BY idit

HAVING AVG(score)>=80;io

在這裏,若是用WHERE代替HAVING就會出錯。table

 

使用示例************************************************************************************

計算每種物料入庫總數大於當前庫存的最先一筆入庫的時間

select productid,inamount,DATEDIFF(day,operatedate,getdate()) from(
select row_number() over(partition by productid order by operatedate) as rownum,*
from (select p.productid,p.inamount,k.operatedate from
(select productid,isnull(sum(amount),0) as inamount from P_ProductBillSumTab a with(nolock)
where tagid in ('1101','1102','1105','1106') group by productid having isnull(sum(amount),0)>(select sum(storage) as storate from p_productbatchtab b with(nolock)
where productid=a.productid)) p
left join P_ProductBillSumTab k with(nolock) on k.productid=p.productid) as mm) as T
where T.rownum = 1 order by operatedate

****************************************************************************************************

select *,DATEDIFF(day,t.operatedate,getdate()) from ((select row_number() over(partition by productid order by samount) as rownum,* from(select aa.*,c.storage from (select productid,amount,operatedate,(select SUM(amount) from product_inlist b where b.productid=a.productid and b.id>=a.id) as samountfrom product_inlist a)aaleft join product_storage c on c.productid=aa.productidwhere samount>c.storage ) k )) as T where T.rownum = 1order by operatedate desc

相關文章
相關標籤/搜索