| Author |
Topic |
|
NguyenL71
Posting Yak Master
228 Posts |
Posted - 2010-06-03 : 11:09:26
|
| I have MS Access table and need to convert the columns to rows. There is 50 states (column names) in #accessTable. Also,I only want to convert these columns which has value = 1 match with #StateCode and return stateid.Below is the business rule and desired results. SQL 2005.Thank you so much in advance.IF OBJECT_ID('Tempdb.dbo.#AccessTable ', 'u') IS NOT NULL DROP TABLE #AccessTable GOCREATE TABLE #AccessTable ( CustId INT NULL, AL TINYINT NULL, AK TINYINT NULL, AZ TINYINT NULL, AR TINYINT NULL, CA TINYINT NULL, CO TINYINT NULL)GOINSERT INTO #AccessTable (CustId, AL, AK, AZ, AR, CA, CO) VALUES (7814, 1, 1, 0, 1, 1, 0)INSERT INTO #AccessTable (CustId, AL, AK, AZ, AR, CA, CO) VALUES (8947, 1, 1, 1, 0, 1, 1)INSERT INTO #AccessTable (CustId, AL, AK, AZ, AR, CA, CO) VALUES (9871, 1, 0, 1, 0, 0, 1)GO SELECT * FROM #AccessTable; go CustId AL AK AZ AR CA CO----------- ---- ---- ---- ---- ---- ----7814 1 1 0 1 1 08947 1 1 1 0 1 19871 1 0 1 0 0 1IF OBJECT_ID('Tempdb.dbo.#StateCode ', 'u') IS NOT NULL DROP TABLE #StateCodeGOCREATE TABLE #StateCode( StateId INT NULL, StateCd CHAR(2) NULL)GOINSERT INTO #StateCode VALUES (1, 'AL')INSERT INTO #StateCode VALUES (2, 'AK')INSERT INTO #StateCode VALUES (3, 'AZ')INSERT INTO #StateCode VALUES (4, 'AR')INSERT INTO #StateCode VALUES (5, 'CA')INSERT INTO #StateCode VALUES (6, 'CO')GO SELECT * FROM #StateCode; GO StateId StateCd----------- -------1 AL2 AK3 AZ4 AR5 CA6 CO SELECT * FROM #AccessTable; go -- Business Rule: Convert only these columns = 1 skip 0. -- Result want:CustId StateId------ -------7814 17814 27814 47814 58947 18947 28947 38947 58947 69871 19871 39871 6 |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2010-06-03 : 11:24:28
|
Try thisselect a.CustId,b.StateId from(select CustId,States from(SELECT * FROM #AccessTable) pUNPIVOT (Codes for States IN (AL,AK,AZ,AR,CA,CO)) as unpvtwhere Codes = 1) ainner join #StateCode b on a.States = b.StateCd |
 |
|
|
NguyenL71
Posting Yak Master
228 Posts |
Posted - 2010-06-03 : 11:34:47
|
Thanks so much for helping.quote: Originally posted by vijayisonly Try thisselect a.CustId,b.StateId from(select CustId,States from(SELECT * FROM #AccessTable) pUNPIVOT (Codes for States IN (AL,AK,AZ,AR,CA,CO)) as unpvtwhere Codes = 1) ainner join #StateCode b on a.States = b.StateCd
|
 |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2010-06-03 : 11:36:08
|
| Np. You're welcome. |
 |
|
|
|
|
|