Skip to content

Commit c63d66a

Browse files
HAVING
1 parent ecc3cf2 commit c63d66a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

SELECT CLAUSE 2/SQL HAVING.sql

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
-- The SQL HAVING clause is used if we need to filter the result set based on aggregate functions such as MIN() and MAX(), SUM() and AVG(), and COUNT().
2+
-- The HAVING clause is used in combination with the GROUP BY clause to filter groups based on a specified condition.
3+
4+
-- Syntax:
5+
/*
6+
SELECT column1, column2, aggregate_function(column3)
7+
FROM table_name
8+
WHERE condition
9+
GROUP BY column1, column2
10+
HAVING condition;
11+
*/
12+
13+
-- Example: select STUDENTS with the same NAME based on their ROLL count
14+
15+
SELECT name, COUNT(roll) AS Count
16+
FROM students
17+
GROUP BY name
18+
HAVING COUNT(roll) > 1;
19+
20+
-- Example: Select the count of customer ids greater than one and their corresponding country
21+
22+
SELECT COUNT(id), country
23+
FROM customers
24+
GROUP BY country
25+
HAVING COUNT(id) > 1;
26+
27+
-- with the HAVING clause, we can use an aggregate function like SUM to calculate the sum of amounts in the order table and get the total order value of less than 5000 for each
28+
29+
SELECT customer_id, SUM(price) AS Total
30+
FROM order_details
31+
GROUP BY customer_id
32+
HAVING SUM(price) < 5000;

SQL.session.sql

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
select *,
2+
case
3+
when age > any (select age from teachers) then 'Declined'
4+
else 'Approved'
5+
end as Status
6+
from students;

0 commit comments

Comments
 (0)