| Next Tip?
Home » Database Questions, MsSql Server

Write query to get custom results

8 February 2010 358 views One Comment
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...

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: 27% [?]

Post to Twitter Tweet This Post

Related interview questions

One Comment »

  • gaurav.arora said:

    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.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes