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.
| Author |
Topic |
|
NguyenL71
Posting Yak Master
228 Posts |
Posted - 2011-01-11 : 13:54:00
|
| [code]Hi all,Given the table and data below. How can I get the desired output below. Basislly, convert columns data into rows.Thanks in advance.DROP TABLE [dbo].[StagingCust]GOCREATE TABLE [dbo].[StagingCust]( [CustomerID] [varchar](5) NULL, [ContactLastName1] [varchar](10) NULL, [ContactFirstName1] [varchar](10) NULL, [ContactLastName2] [varchar](10) NULL, [ContactFirstName2] [varchar](10) NULL, [ContactLastName3] [varchar](10) NULL, [ContactFirstName3] [varchar](10) NULL) ON [PRIMARY]GOSET NOCOUNT ON;SET XACT_ABORT ON;GOBEGIN TRANSACTION;INSERT INTO [dbo].[StagingCust]([CustomerID], [ContactLastName1], [ContactFirstName1], [ContactLastName2], [ContactFirstName2], [ContactLastName3], [ContactFirstName3])SELECT N'BOA', N'Smith ', N'Lisa', N'Lee', N'Peter', N'Nguyen', N'Peter' UNION ALLSELECT N'KON', N'Lorenze', N'Marine', N'Melissa', N'Bloch', 'Doe', N'User3'COMMIT;RAISERROR (N'[dbo].[StagingCust]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;GO--Testing.. SELECT CustomerID, CASE LName WHEN 1 THEN ContactLastName1 WHEN 2 THEN ContactLastName2 WHEN 3 THEN ISNULL(ContactLastName3, '') END AS 'LastName' FROM StagingCust CROSS JOIN (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS a(LName) go SELECT * FROM StagingCust; go -- Desired output:CustomerID LastName FirstName---------- ---------- ---------BOA Smith LisaBOA Lee PeterBOA Nguyen PeterKON Lorenze MarineKON Melissa BlochKON Doe User3[/code] |
|
|
mikgri
Starting Member
39 Posts |
Posted - 2011-01-13 : 09:47:26
|
| Try this: SELECT CustomerID=case LNAME when 4 then '' else CustomerID end, CASE LName WHEN 1 THEN ContactLastName1 WHEN 2 THEN ContactLastName2 WHEN 3 THEN ISNULL(ContactLastName3, '') when 4 then '' END AS 'LastName', CASE LName WHEN 1 THEN ContactFirstName1 WHEN 2 THEN ContactFirstName2 WHEN 3 THEN ISNULL(ContactFirstName3, '') when 4 then '' END AS 'FirstName' FROM StagingCust CROSS JOIN (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL select 4) AS a(LName) |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
|
|
|
|
|
|