Tags
Average Marks Puzzle, Complex SQL Challenges, complex sql statement(puzzle), Complex TSQL Challenge, Interesting Interview Questions, Interview Qs.SQL SERVER Questions, Interview questions on Joins, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Joins, Joins Interview questions, Joins Puzzle, Khowal, Learn complex SQL, Learn SQL, Learn T-SQL, Objective Puzzle, Pawan, Pawan Khowal, Pawan Kumar, Pawan Kumar Khowal, PL/SQL Challenges, puzzle sql developer, Puzzles, Queries for SQL Interview, SELECT Puzzle, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL Interview Questions, SQL Joins, SQL pl/sql puzzles, SQL Puzzles, SQL Queries, SQL Quiz, SQL Server Database, SQL SERVER Interview questions, SQL Skills, SQL Sudoku, SQL Top clause, SQL Trikcy question, sql/database interview for puzzle sql developer, SQLSERVER, T SQL Puzzles, T-SQL Challenge, T-SQL Query | [ The Complex Week Puzzle ], The Biggest Gap Puzzle, The Gap Puzzle, TOP Clause, Tough SQL Challenges, Tough SQL Puzzles, Tricky Questions, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries, Week puzzle
T-SQL Query | [ The Average Marks Puzzle ]
Puzzle Statement
- The puzzle is simple.
- You have to list out student information where the student scored more than the Average Marks per subject.
- Please check out the sample input and expected output for details.
Sample Input
Sname | SMarks | SSubject |
A | 10 | X |
B | 20 | X |
C | 30 | Y |
D | 40 | Y |
Expected Output
Sname | SMarks | SSubject |
B | 20 | X |
D | 40 | Y |
Rules/Restrictions
- The solution should be should use “SELECT” statement or “CTE”.
- Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com
Script
Use the below script to generate the source table and fill them up with the sample data.
—
CREATE TABLE Neeraj ( Sname VARCHAR(1) ,SMarks INT ,SSubject VARCHAR(1) ) GO INSERT INTO Neeraj(Sname, SMarks , SSubject) VALUES ('A' , 10 , 'X'), ('B' , 20 , 'X'), ('C' , 30 , 'Y'), ('D', 40 , 'Y') — |
Update May 10 | Solutions — Pawan Kumar Khowal
-- /************ SOLUTION 1 ****************/ SELECT n.*, Ag FROM Neeraj n INNER JOIN ( SELECT AVG(SMarks) Ag , SSubject FROM Neeraj GROUP BY SSubject ) a on a.SSubject = n.SSubject WHERE SMarks > Ag /************ SOLUTION 2 ****************/ SELECT * FROM Neeraj n WHERE SMarks > ( SELECT AVG(SMarks) ag FROM Neeraj n1 WHERE n1.SSubject = n.SSubject GROUP BY SSubject ) -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
Http://MSBISkills.com
;WITH CTE
AS
(
SELECT *,AVG(SMarks)OVER(PARTITION BY SSubject) Ag
FROM #Neeraj
)
SELECT Sname,SMarks,SSubject
FROM CTE
WHERE SMarks>Ag
LikeLike