Below is my data in table :
| 1 | 1M |
| 2 | 1M |
| 3 | 1M |
| 4 | 1M |
| 5 | 1M |
| 6 | 1M |
| 7 | 1M |
| 8 | 1M |
| 9 | 1M |
| 10 | 1M |
and i want output like below
| 1M | 1 | 2 | 3 |
| 1M | 4 | 5 | 6 |
| 1M | 7 | 8 | 9 |
| 1M | 10 |
Thanks
| 1 | 1M |
| 2 | 1M |
| 3 | 1M |
| 4 | 1M |
| 5 | 1M |
| 6 | 1M |
| 7 | 1M |
| 8 | 1M |
| 9 | 1M |
| 10 | 1M |
| 1M | 1 | 2 | 3 |
| 1M | 4 | 5 | 6 |
| 1M | 7 | 8 | 9 |
| 1M | 10 |
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rasadul Alam RashedPosted May 16, 2013, 4:25 AM
http://cybarlab.com/sql-query-to-convert-column-to-row
Apurva MehtaPosted May 13, 2013, 6:14 AM
INPUT
QUERY
Select Number, ( Case When (Number = '1M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 0 ) OR (Number = '2M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 0 )
OR
(Number = '3M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 0 )
Then Id End ) As A, ( Case When (Number = '1M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 2 ) OR
(Number = '2M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 2 )
OR
(Number = '3M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 2 )
Then Id End ) As B, ( Case When (Number = '1M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 1 )
OR
(Number = '2M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 1 )
OR
(Number = '3M' AND ROW_NUMBER() OVER(ORDER BY [Id] DESC) % 3 = 1 )
Then Id End ) As CFrom
TEST ORDER BY Id
OutPut
Required Output :
Any idea , how to remove null and shift cell up.
PS : Using SQL Server 2008 R2
Jignesh TrivediPosted May 10, 2013, 3:43 AM
hi,
I think this is not possible with Pivot Query because Pivot Query must have some aggregate function.
so you have think differently to resolve the issue.
i have tried some code and share here
--drop table #test
Create table #test
(
Id int,
Name varchar(20)
)
Insert into #test values(1,'1M')
Insert into #test values(2,'1M')
Insert into #test values(3,'1M')
Insert into #test values(4,'1M')
Insert into #test values(5,'1M')
Insert into #test values(6,'1M')
Insert into #test values(7,'1M')
Insert into #test values(8,'1M')
Insert into #test values(9,'1M')
Insert into #test values(10,'1M')
declare @max int
declare @id int = 1
declare @pkid int = 1
select @max = MAX(id) from #test
declare @d1 table
(
DatabaseID int,
PId int,
Name varchar(10)
)
declare @d2 table
(
DatabaseID int,
PId int
)
declare @d3 table
(
DatabaseID int,
PId int
)
While @id <= @max
begin
if(@id <= @max)
insert into @d1 values(@pkid,@id, '1M')
set @id+=1
if(@id <= @max)
insert into @d2 values(@pkid,@id)
set @id+=1
if(@id <= @max)
insert into @d3 values(@pkid,@id)
set @id+=1
set @pkid +=1
end
select d1.Name,d1.PId,d2.PId,d3.PId from @d1 d1
LEFT Outer join @d2 d2 on d1.DatabaseID = d2.DatabaseID
LEFT Outer join @d3 d3 on d1.DatabaseID = d3.DatabaseID
hope this will help you.