Write query to get custom results
This question is asked in recent interview, following is the scenario:
Q. I have a following table :
| University | UtoTal | Status | StatusCnt |
| U1 | 100 | Pending | 20 |
| U1 | 100 | Active | 20 |
| U1 | 100 | Deferred | 60 |
| U2 | 60 | Pending | 20 |
| U2 | 60 | Active | 20 |
| U2 | 60 | Deferred | 20 |
I want results as :
| University | UtoTal | Status | StatusCnt |
| U1 | 100 | Pending | 20 |
| Active | 20 | ||
| Deferred | 60 | ||
| U2 | 60 | Pending | 20 |
| Active | 20 | ||
| Deferred | 20 |
Ans: At the time of interview I wasn’t easy with the answer but I wrote a query, but interviewer not satisfied.
I got the following proper query/solution from one of my colleagues Mr. sandeep Walia:
declare @tbl table(university varchar(100),Utotals int, status varchar(100),statuscnt int)
insert into @tbl(university,Utotals,status,statuscnt)
select ‘u1′,100,’pending’,20
union all
select ‘u1′,100,’Active’,20
union all
select ‘u1′,100,’Deferred’,60
union all
select ‘u2′,60,’pending’,20
union all
select ‘u2′,60,’Active’,20
union all
select ‘u2′,60,’Deferred’,20
select * from @tbl;
with cte as (
SELECT ROW_NUMBER() OVER(PARTITION BY university ORDER BY university DESC) AS RowID,
*
FROM @tbl
)
SELECT case when rowid=1 then university else null end university,case when rowid=1 then Utotals else null end Utotals,status,statuscnt
FROM cte
Popularity: 35% [?]
Related interview questions
- Create dynamic query with dynamic joins
- I need to view the number of tables existing under one particular Owner. Is it possible? If so, pl give the SQL query for this?
- Change date format mm/dd/yy to dd/mm/yy using query?
- When is the results table for the query in a DECLARE CURSOR statement created?
- What is File Status in VSAM?











Great one!
I have requirement where I need to update an existing table, here is the query :
declare @tbl table(id int identity, university varchar(100),Utotals int, status varchar(100),statuscnt int)
insert into @tbl(university,Utotals,status,statuscnt)
select 'u1',100,'pending',20
union all
select 'u1',100,'Active',20
union all
select 'u1',100,'Deferred',60
union all
select 'u2',60,'pending',20
union all
select 'u2',60,'Activ',20
union all
select 'u2',60,'Deferred',20
select * from @tbl
update tt
set university=null,
utotals=null
from @tbl tt inner join @tbl t2 on tt.id = t2.id + 1
and tt.university = t2.university
select * from @tbl
Leave your response!
You must be logged in to post a comment.