Tags
Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Learn complex SQL, Learn SQL, Learn T-SQL, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SQL 2012, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL pl/sql puzzles, SQL Puzzles, SQL SERVER Interview questions, SQL SERVER2005/2008, SQL Sudoku, SQLSERVER, SSRS Interview Questions, T SQL Puzzles, T-SQL Challenge, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
T-SQL Query | [ Print Male and Female Alternate Puzzle ] – In this puzzle we have print male and female alternate from the sample input table. Please check out the sample input and expected output for details.
Sample Input
ID | NAME | GENDER |
1 | Neeraj | M |
2 | Mayank | M |
3 | Pawan | M |
4 | Gopal | M |
5 | Sandeep | M |
6 | Isha | F |
7 | Sugandha | F |
8 | kritika | F |
Expected Output
ID | NAME | GENDER |
1 | Neeraj | M |
6 | Isha | F |
2 | Mayank | M |
7 | Sugandha | F |
3 | Pawan | M |
8 | kritika | F |
4 | Gopal | M |
5 | Sandeep | M |
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.
–Print alternate male and female puzzle–Create table
CREATE TABLE dbo.AlternateMaleFemale ( ID INT ,NAME VARCHAR(10) ,GENDER VARCHAR(1) ) GO --Insert data INSERT INTO dbo.AlternateMaleFemale(ID,NAME,GENDER) VALUES (1,'Neeraj','M'), (2,'Mayank','M'), (3,'Pawan','M'), (4,'Gopal','M'), (5,'Sandeep','M'), (6,'Isha','F'), (7,'Sugandha','F'), (8,'kritika','F') --Verify Data SELECT ID,NAME,GENDER FROM AlternateMaleFemale |
Update May 14 | Solution
-- /************ SOLUTION 1 | Pawan Kumar Khowal ****************/ ;WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY GENDER ORDER BY ID) rnk FROM AlternateMaleFemale ) SELECT * FROM CTE ORDER BY rnk,ID -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
SELECT ID,NAME,GENDER FROM #AlternateMaleFemale
order by RANK()over(partition by gender order by id),GENDER desc
LikeLiked by 1 person
WITH CTE AS (SELECT name,
,GENDER
,ID
,ROW_NUMBER()OVER(PARTITION BY GENDER ORDER BY GENDER) R
FROM INPUT)
SELECT ROW_NUMBER()OVER(PARTITION BY R ORDER BY GENDER DESC) AS ID
,NAME
,GENDER
FROM CTE
LikeLike