Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SQL query question

Author  Topic 

chih
Posting Yak Master

154 Posts

Posted - 2009-01-08 : 22:15:30
Hi All,

I am writing a query which can give me a kind of report. the below is just a simple version.
what i want to do is to split one single column to a table with 3 columns.

declare @pvt table
( a1 int)

INSERT INTO @pvt VALUES (1)
INSERT INTO @pvt VALUES (2)
INSERT INTO @pvt VALUES (3)
INSERT INTO @pvt VALUES (4)
INSERT INTO @pvt VALUES (5)
INSERT INTO @pvt VALUES (6)
INSERT INTO @pvt VALUES (7)
INSERT INTO @pvt VALUES (8)
INSERT INTO @pvt VALUES (9)

if the result is 1,2,3 then in the first column
if the result is 4,5 then in the second column
if the result is 6,7,8,9 then in the third column

The is the result I want
R1 R2 R3
1 4 6
2 5 7
3 null 8
null null 9

Anyone has an idea how to do it? Thank you

ashishashish
Constraint Violating Yak Guru

408 Posts

Posted - 2009-01-08 : 23:55:27
u Can Use Pivot for this purpose if u use Sql 2005.....

or give ur whole data and query u use to do this..

Thanks,,,,

Go to Top of Page

PeterNeo
Constraint Violating Yak Guru

357 Posts

Posted - 2009-01-09 : 00:06:34
try something like this if performance is not a concern

DECLARE @pvt TABLE( a1 INT )

INSERT INTO @pvt VALUES (1)
INSERT INTO @pvt VALUES (2)
INSERT INTO @pvt VALUES (3)
INSERT INTO @pvt VALUES (4)
INSERT INTO @pvt VALUES (5)
INSERT INTO @pvt VALUES (6)
INSERT INTO @pvt VALUES (7)
INSERT INTO @pvt VALUES (8)
INSERT INTO @pvt VALUES (9)

; WITH CTE (R1, R2, R3, Seq)
AS
(
SELECT CASE WHEN A1 IN (1, 2, 3) THEN A1 END,
CASE WHEN A1 IN (4, 5) THEN A1 END,
CASE WHEN A1 IN (6, 7, 8, 9) THEN A1 END,
Seq
FROM (SELECT *, CASE WHEN A1 IN (1, 2, 3) THEN 1
WHEN A1 IN (4, 5) THEN 2
WHEN A1 IN (6, 7, 8, 9) THEN 3
END AS 'Seq'
FROM @pvt) P
)

SELECT MAX(R1) AS R1, MAX(R2) AS R2, MAX(R3) AS R3
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Seq ORDER BY Seq) AS 'Ord' FROM CTE
) X
GROUP BY Ord



"There is only one difference between a dream and an aim.
A dream requires soundless sleep to see,
whereas an aim requires sleepless efforts to achieve..!!"
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2009-01-12 : 12:13:46
Hi,

Try Like this

Create table #table ( val int identity(1,1),id1 int , id2 int, id3 int)
insert into #table
select null,null, a1 from @pvt where a1 > 5 and a1 < = 9

update #table
set id1 = val
where val > = 1 and val< 4

update #table
set id2 = id1+3
where id1 > = 1 and id1 <= 2
and val <>3

select id1, id2, id3 from #table

Be Cool...
Go to Top of Page
   

- Advertisement -