Get the App
SLTechnology News&Howtos  ›  Database  › 

How to rewrite max/min function in Database

Shulou Source: shulou.com Published: 2022-05-31 14:52:28 09月19日 Update

This article mainly introduces how to rewrite the max/min function in the database, the article is very detailed, has a certain reference value, interested friends must read it!

1.OLD:

SELECT a.deptno, a.min_no, mi.ename AS min_n, ma.empno AS max_n FROM (SELECT deptno, MIN (empno) AS min_no, MAX (empno) AS max_no FROM emp GROUP BY deptno) an INNER JOIN emp mi ON (mi.deptno = a.deptno AND mi.empno = a.min_no) INNER JOIN emp ma ON (ma.deptno = a.deptno AND ma.empno = a.max_no)

two。 Direction of optimization:

Sql requirements display the largest employee number and name, the minimum employee number and name in each department

Group by cannot display both aggregate results and source data, so it needs to be done through self-connection.

Using the analysis function, the metadata and aggregated data are displayed in the same row, removing the self-join.

Select deptno, min (empno) min_no, min (ename) keep (dense_rank first order by empno) min_n, max (empno) max_no, min (ename) keep (dense_rank last order by empno) max_nfrom empgroup by deptno; are all the contents of this article "how to rewrite max/min functions in the database". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Data function database content employee name article maximum minimum line value interest at the same time guys partners direction more knowledge results industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Microsoft Linux Docker OPPO Reno