Sqlserver 獲取每組中的第一條記錄
在日常生活方面,我們經(jīng)常需要記錄一些操作,類似于日志的操作,最后的記錄才是有效數(shù)據(jù),而且可能它們屬于不同的方面、功能下面,從數(shù)據(jù)庫的術(shù)語來說,就是查找出每組中的一條數(shù)據(jù)。下面我們要實現(xiàn)的就是在sqlserver中實現(xiàn)從每組中取出第一條數(shù)據(jù)。
例子
![](/d/20211017/2e633daabfb51ef8b0627849817b90e2.gif)
我們要從上面獲得的有效數(shù)據(jù)為:
![](/d/20211017/a72000c3e1ce62f4713590f0edc1282d.gif)
對應的sql語句如下所示:
select * from t1 t where id = (select top 1 id from t1 where grp = t.grp order by createtime desc )
下面給大家介紹oracle查詢?nèi)〕雒拷M中的第一條記錄
oracle查詢:取出每組中的第一條記錄
按type字段分組,code排序,取出每組中的第一條記錄
方法一:
select type,min(code) from group_info
group by type;
注意:select 后面的列要在group by 子句中,或是用聚合函數(shù)包含,否則會有語法錯誤。
方法二:
SELECT * FROM(
SELECT z.type , z.code ,ROW_NUMBER()
OVER(PARTITION BY z.type ORDER BY z.code) AS code_id
FROM group_info z
)
WHERE code_id =1;
這里涉及到的over()是oracle的分析函數(shù)
參考sql reference文檔:
Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group.
Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE , GROUP BY , and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
語法結(jié)構(gòu):
analytic_function ([ arguments ]) OVER
(analytic_clause)
其中analytic_clause結(jié)構(gòu)包括:
[ query_partition_clause ]
[ order_by_clause [ windowing_clause ] ]
也就是:函數(shù)名( [ 參數(shù) ] ) over( [ 分區(qū)子句 ] [ 排序子句 [ 滑動窗口子句 ] ])
這里PARTITION BY 引導的分區(qū)子句類似于聚組函數(shù)中的group by,排序子句可看成是select語句中的order by.
mysql 中只獲取1條數(shù)據(jù)
SELECT * FROM 表 LIMIT 0, 10
LIMIT 接受一個或兩個數(shù)字參數(shù)。
參數(shù)必須是一個整數(shù)常量。
如果給定兩個參數(shù),第一個參數(shù)指定第一個返回記錄行的偏移量,
第二個參數(shù)指定返回記錄行的最大數(shù)目。
初始記錄行的偏移量是 0(而不是 1)
主意:limit 用于 having 之后
自己的示例:
select count(1),tpc_equipment_code from tb_parts_consume GROUP BY tpc_equipment_code ORDER BY count(1) DESC LIMIT 1;
您可能感興趣的文章:- ADO.NET 連接數(shù)據(jù)庫字符串小結(jié)(Oracle、SqlServer、Access、ODBC)
- c#幾種數(shù)據(jù)庫的大數(shù)據(jù)批量插入(SqlServer、Oracle、SQLite和MySql)
- sqlserver、Mysql、Oracle三種數(shù)據(jù)庫的優(yōu)缺點總結(jié)
- sqlserver實現(xiàn)oracle的sequence方法
- 深入Mysql,SqlServer,Oracle主鍵自動增長的設(shè)置詳解
- oracle,mysql,SqlServer三種數(shù)據(jù)庫的分頁查詢的實例
- oracle連接ODBC sqlserver數(shù)據(jù)源的詳細步驟