Subquery 4 (use subquery in select clause), select clause

Source: Internet
Author: User
Tags dname

Subquery 4 (use subquery in select clause), select clause

Example 1,Query the number, name, location, department count, and average salary of each department.

SELECT d.deptno,d.dname,d.loc,  (SELECT  COUNT(empno) FROM emp WHERE emp.deptno=d.deptno GROUP BY deptno) con,  (SELECT AVG(sal) FROM emp WHERE emp.deptno=d.deptno GROUP BY deptno) avgsalFROM dept d
WITH clause

Example 2,Use the with clause to define data in the emp table as a temporary table

WITH e AS(SELECT * FROM emp)SELECT * FROM e;

Example 3,Query the number, name, location, average department salary, and number of people of each department

-- Query the ID, name, location, average department salary, number of people WITH e AS (SELECT deptno dno, ROUND (AVG (sal), 2) avgsal, COUNT (empno) con FROM emp group by deptno) SELECT d. deptno, d. dname, d. loc, e. avgsal, e. conFROM dept d, eWHERE d. deptno = e. dno (+ );

Example 4,Query the employee ID, name, position, employment date, salary, department ID, and department name of each department. The result is sorted by department ID.

WITH e AS(   SELECT deptno dno,MAX(sal) maxsal   FROM emp   GROUP BY deptno)SELECT em.ename,em.job,em.hiredate,em.sal,d.deptno,d.dnameFROM emp em,dept d,eWHERE em.deptno=e.dno       AND em.sal=e.maxsal       AND d.deptno=e.dno       ORDER BY em.deptno;

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.