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 2000 Forums
 Transact-SQL (2000)
 PIVOT - sorry broken record

Author  Topic 

rgombina
Constraint Violating Yak Guru

319 Posts

Posted - 2008-11-25 : 09:34:42
Please help again...

I just need a statement to flatten rows to one.

Data:

ID Col1 Col2 Col3
1 val1
1 val2
1 val3

Desired result:
ID Col1 Col2 Col3
1 val1 val2 val3


Thanks and I will study some more of these stuff so I don't have to ask, again.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-25 : 09:51:09
SELECT MIN(col1), SUM(col1) - max(col1) - min(col1), max(col1)
FROM Table1
GROUP BY id



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

rgombina
Constraint Violating Yak Guru

319 Posts

Posted - 2008-11-25 : 09:57:36
Thanks for the quick reply. What if my values are strings "val1", "val2", "val3"?
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-25 : 09:59:59
Or more precisely
http://weblogs.sqlteam.com/peterl/archive/2008/11/25/Easy-sorted-numeric-pivoting-with-maximum-three-columns.aspx


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-25 : 10:06:00
VARCHAR?
-- Prepare sample data
DECLARE @Sample TABLE
(
ID INT,
col VARCHAR(9)
)

INSERT @Sample
SELECT 0, '1' UNION ALL
SELECT 0, '1' UNION ALL
SELECT 0, '2' UNION ALL
SELECT 1, '1' UNION ALL
SELECT 1, '2' UNION ALL
SELECT 1, '3' UNION ALL
SELECT 2, '5' UNION ALL
SELECT 2, '5' UNION ALL
SELECT 2, '5' UNION ALL
SELECT 3, '6' UNION ALL
SELECT 3, '6' UNION ALL
SELECT 5, '8' UNION ALL
SELECT 5, '9' UNION ALL
SELECT 4, '7'

-- Stage the source data
DECLARE @Stage TABLE
(
ID INT,
rowID INT IDENTITY(0, 1),
col VARCHAR(9)
)

INSERT @Stage
(
ID,
col
)
SELECT ID,
col
FROM @Sample
ORDER BY ID,
col

-- Display the data
SELECT ID,
MAX(CASE WHEN recID = 0 THEN col ELSE NULL END) AS col1,
MAX(CASE WHEN recID = 1 THEN col ELSE NULL END) AS col2,
MAX(CASE WHEN recID = 2 THEN col ELSE NULL END) AS col3
FROM (
SELECT s.ID,
s.rowID - t.rowID AS recID,
s.col
FROM @Stage AS s
INNER JOIN (
SELECT ID,
MIN(rowID) AS rowID
FROM @Stage
GROUP BY ID
) AS t ON t.ID = s.ID
) AS d
GROUP BY ID
ORDER BY ID



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

rgombina
Constraint Violating Yak Guru

319 Posts

Posted - 2008-11-25 : 10:44:49
Thanks!!!
Go to Top of Page
   

- Advertisement -