」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > SQL過濾和分類現實示例

SQL過濾和分類現實示例

發佈於2025-03-25
瀏覽:829

SQL Filtering and Sorting with Real-life Examples

This blog explains the SQL clauses like WHERE, HAVING, ORDER BY, GROUP BY, and other related clauses using real-life examples with the employees and departments tables.

Table of Contents

  1. Tables Structure
  2. WHERE Clause
  3. GROUP BY Clause
  4. HAVING Clause
  5. ORDER BY Clause
  6. LIMIT Clause
  7. DISTINCT Clause
  8. AND, OR, NOT Operators

Tables Structure

employees Table

emp_id name age department_id hire_date salary
1 John Smith 35 101 2020-01-01 5000
2 Jane Doe 28 102 2019-03-15 6000
3 Alice Johnson 40 103 2018-06-20 7000
4 Bob Brown 55 NULL 2015-11-10 8000
5 Charlie Black 30 102 2021-02-01 5500

departments Table

dept_id dept_name
101 HR
102 IT
103 Finance
104 Marketing

WHERE Clause

The WHERE clause is used to filter records based on specified conditions.

SQL Query

SELECT name, age, salary
FROM employees
WHERE age > 30;

Result

name age salary
John Smith 35 5000
Alice Johnson 40 7000
Bob Brown 55 8000

Explanation: The WHERE clause filters the rows to include only employees who are older than 30 years.

Example with AND Operator

SELECT name, age, salary
FROM employees
WHERE age > 30 AND salary > 5000;

Result

name age salary
Alice Johnson 40 7000
Bob Brown 55 8000

Explanation: The WHERE clause filters employees who are older than 30 and have a salary greater than 5000.


GROUP BY Clause

The GROUP BY clause is used to group rows that have the same values into summary rows, like finding the number of employees in each department.

SQL Query

SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;

Result

department_id employee_count
101 1
102 2
103 1

Explanation: The GROUP BY clause groups employees by department_id and counts the number of employees in each department.


HAVING Clause

The HAVING clause is used to filter groups created by the GROUP BY clause. It works like the WHERE clause but is used after aggregation.

SQL Query

SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 5500;

Result

department_id avg_salary
102 5750
103 7000

Explanation: The HAVING clause filters the groups based on the average salary of employees in each department. Only departments with an average salary greater than 5500 are included.


ORDER BY Clause

The ORDER BY clause is used to sort the result set by one or more columns. By default, it sorts in ascending order; to sort in descending order, use DESC.

SQL Query (Ascending Order)

SELECT name, salary
FROM employees
ORDER BY salary;

Result

name salary
John Smith 5000
Charlie Black 5500
Jane Doe 6000
Alice Johnson 7000
Bob Brown 8000

Explanation: The result is sorted by salary in ascending order.

SQL Query (Descending Order)

SELECT name, salary
FROM employees
ORDER BY salary DESC;

Result

name salary
Bob Brown 8000
Alice Johnson 7000
Jane Doe 6000
Charlie Black 5500
John Smith 5000

Explanation: The result is sorted by salary in descending order.


LIMIT Clause

The LIMIT clause is used to specify the number of records to return from the result set. This is particularly useful for paging or limiting large result sets.

SQL Query

SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;

Result

name salary
Bob Brown 8000
Alice Johnson 7000
Jane Doe 6000

Explanation: The LIMIT clause restricts the output to only the top 3 highest-paid employees.


DISTINCT Clause

The DISTINCT clause is used to return only distinct (different) values in a result set, removing duplicates.

SQL Query

SELECT DISTINCT department_id
FROM employees;

Result

department_id
101
102
103

Explanation: The DISTINCT clause returns unique department_id values, eliminating duplicates.


AND, OR, NOT Operators

The AND, OR, and NOT operators are used to combine multiple conditions in the WHERE clause.

AND Operator

The AND operator is used to combine two or more conditions. The result will include only rows where all conditions are true.

SELECT name, age, salary
FROM employees
WHERE age > 30 AND salary > 5500;

Result

name age salary
Alice Johnson 40 7000
Bob Brown 55 8000

Explanation: The WHERE clause filters rows where both conditions (age > 30 and salary > 5500) are true.

OR Operator

The OR operator is used when only one of the conditions must be true.

SELECT name, age, salary
FROM employees
WHERE age  7000;

Result

name age salary
Jane Doe 28 6000
Alice Johnson 40 7000
Bob Brown 55 8000

Explanation: The WHERE clause filters rows where either age 7000 is true.

NOT Operator

The NOT operator is used to exclude rows where a condition is true.

SELECT name, age, salary
FROM employees
WHERE NOT salary > 6000;

Result

name age salary
John Smith 35 5000
Charlie Black 30 5500
Jane Doe 28 6000

Explanation: The WHERE clause filters rows where salary > 6000 is false, meaning it returns employees earning 6000 or less.


Conclusion

This blog explains how to filter, group and sort data using SQL’s WHERE, HAVING, ORDER BY, GROUP BY, and other clauses with real-life examples from the employees and departments tables. Understanding these clauses is fundamental for writing efficient SQL queries, analyzing data, and managing databases effectively.

版本聲明 本文轉載於:https://dev.to/milliemolotov/sql-filtering-and-sorting-with-real-life-examples-58gb?1如有侵犯,請聯繫[email protected]刪除
最新教學 更多>
  • 為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    為什麼使用固定定位時,為什麼具有100%網格板柱的網格超越身體?
    網格超過身體,用100%grid-template-columns 為什麼在grid-template-colms中具有100%的顯示器,當位置設置為設置的位置時,grid-template-colly修復了? 問題: 考慮以下CSS和html: class =“ snippet-code”> ...
    程式設計 發佈於2025-03-31
  • 如何在php中使用捲髮發送原始帖子請求?
    如何在php中使用捲髮發送原始帖子請求?
    如何使用php 創建請求來發送原始帖子請求,開始使用curl_init()開始初始化curl session。然後,配置以下選項: curlopt_url:請求 [要發送的原始數據指定內容類型,為原始的帖子請求指定身體的內容類型很重要。在這種情況下,它是文本/平原。要執行此操作,請使用包含以下標頭...
    程式設計 發佈於2025-03-31
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript [#1089-不正確的前綴鍵在嘗試在表中創建一個prefix鍵時會出現。前綴鍵旨在索引字符串列的特定前綴長度長度,可以更快地搜索這些前綴。 了解prefix keys `這將在整個Movie_ID列上創建標準主鍵。主密鑰對於唯一識...
    程式設計 發佈於2025-03-31
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-03-31
  • 如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
    如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
    為有效的slug生成首先,該函數用指定的分隔符替換所有非字母或數字字符。此步驟可確保slug遵守URL慣例。隨後,它採用ICONV函數將文本簡化為us-ascii兼容格式,從而允許更廣泛的字符集合兼容性。 接下來,該函數使用正則表達式刪除了不需要的字符,例如特殊字符和空格。此步驟可確保slug僅包...
    程式設計 發佈於2025-03-31
  • 哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    哪種方法更有效地用於點 - 填點檢測:射線跟踪或matplotlib \的路徑contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    程式設計 發佈於2025-03-31
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-03-31
  • 如何使用不同數量列的聯合數據庫表?
    如何使用不同數量列的聯合數據庫表?
    合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
    程式設計 發佈於2025-03-31
  • 為什麼我的CSS背景圖像出現?
    為什麼我的CSS背景圖像出現?
    故障排除:CSS背景圖像未出現 ,您的背景圖像儘管遵循教程說明,但您的背景圖像仍未加載。圖像和样式表位於相同的目錄中,但背景仍然是空白的白色帆布。 而不是不棄用的,您已經使用了CSS樣式: bockent {背景:封閉圖像文件名:背景圖:url(nickcage.jpg); 如果您的html,cs...
    程式設計 發佈於2025-03-31
  • 您可以使用CSS在Chrome和Firefox中染色控制台輸出嗎?
    您可以使用CSS在Chrome和Firefox中染色控制台輸出嗎?
    在javascript console 中顯示顏色是可以使用chrome的控制台顯示彩色文本,例如紅色的redors,for for for for錯誤消息? 回答是的,可以使用CSS將顏色添加到Chrome和Firefox中的控制台顯示的消息(版本31或更高版本)中。要實現這一目標,請使用以下...
    程式設計 發佈於2025-03-31
  • 您如何在Laravel Blade模板中定義變量?
    您如何在Laravel Blade模板中定義變量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配變量對於存儲以後使用的數據至關重要。在使用“ {{}}”分配變量的同時,它可能並不總是最優雅的解決方案。 幸運的是,Blade通過@php Directive提供了更優雅的方法: $ old_section =...
    程式設計 發佈於2025-03-31
  • 如何從PHP中的數組中提取隨機元素?
    如何從PHP中的數組中提取隨機元素?
    從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。
    程式設計 發佈於2025-03-31
  • 對象擬合:IE和Edge中的封面失敗,如何修復?
    對象擬合:IE和Edge中的封面失敗,如何修復?
    To resolve this issue, we employ a clever CSS solution that solves the problem:position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%)...
    程式設計 發佈於2025-03-31
  • PHP陣列鍵值異常:了解07和08的好奇情況
    PHP陣列鍵值異常:了解07和08的好奇情況
    PHP數組鍵值問題,使用07&08 在給定數月的數組中,鍵值07和08呈現令人困惑的行為時,就會出現一個不尋常的問題。運行print_r($月份)返回意外結果:鍵“ 07”丟失,而鍵“ 08”分配給了9月的值。 此問題源於PHP對領先零的解釋。當一個數字帶有0(例如07或08)的前綴時,PHP...
    程式設計 發佈於2025-03-31
  • 如何在無序集合中為元組實現通用哈希功能?
    如何在無序集合中為元組實現通用哈希功能?
    在未訂購的集合中的元素要糾正此問題,一種方法是手動為特定元組類型定義哈希函數,例如: template template template 。 struct std :: hash { size_t operator()(std :: tuple const&tuple)const {...
    程式設計 發佈於2025-03-31

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3