-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQL_SubQuries.sql
96 lines (71 loc) · 2.01 KB
/
SQL_SubQuries.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
USE Debu;
-- SQL Sub Queries || Inner Queries || Nested Queries
-- it's involved 2 statement
-- 1) write inside SELECT
-- 2) inside FROM
-- 3) inside where Clause
-- Q1: Print those student name who are geeting more marks then college avg.
CREATE TABLE Student(
rollNumber INT PRIMARY KEY,
name VARCHAR(50),
marks INT NOT NULL,
grade VARCHAR(2),
city VARCHAR(20)
);
INSERT INTO Student
(rollNumber,name, marks, grade,city)
VALUES
(101, "Ram", 78, "C", "Pune"),
(102, "Rakesh", 93, "A", "Mumbai"),
(103, "Roshan", 85, "B", "Mumbai"),
(104, "Raj", 96, "A", "Kolkata"),
(105, "Rajesh", 92, "A", "Kolkata"),
(106, "Ramesh", 82, "B", "Delhi");
SELECT * FROM Student;
-- cal the avg of marks.
SELECT AVG(marks)
FROM Student;
-- print those students name only whose marks are greater than class average.
SELECT name , marks
FROM Student
WHERE marks > 87.6667;
-- the above process is static we have to do it dynamic
-- the problem is : suppose some new student will come and some student marks will increase then it will affect in the avg for that
-- without static we have to write dynamic sql quries instatede of static.
SELECT name , marks
FROM Student
WHERE marks > (
SELECT AVG(marks)
FROM Student
);
-- Q2: Print those student name whoes rollNumber is Even.
SELECT rollNumber
FROM Student
WHERE rollNumber % 2 = 0;
SELECT name, rollNumber
FROM Student
WHERE rollNumber IN(
SELECT rollNumber
FROM Student
WHERE rollNumber % 2 = 0
);
-- Q3: Print those students who are getting max marks from Kolkata.
-- cal the max marks.
SELECT MAX(marks)
FROM Student;
SELECT name, city
FROM Student
WHERE marks >= (SELECT MAX(marks)
FROM Student) && city = "Kolkata";
-- find out the st whoes are from "Kolkata"
SELECT name
FROM Student
WHERE city = "Kolkata";
SELECT name, city
FROM Student
WHERE (
marks >= (SELECT MAX(marks)FROM Student) && city = (SELECT name FROM Student WHERE city = "Kolkata")
);
-- Sol is given by Shradha Di.
SELECT MAX(marks)
FROM (SELECT * FROM Student WHERE city = "Kolkata") AS tem;