Create a row for each cell that has data from multiple columns

↘锁芯ラ 提交于 2019-12-07 17:29:28

Use UNPIVOT to normalize your table:

SELECT u.RespondentID, u.Country
FROM @source
UNPIVOT (Country FOR c IN (Andorra, Austria, Belgium, Cyprus, Denmark, Finland, France)) u

@source is a table that contains the data imported from your Excel worksheet.

Test data:

DECLARE @source TABLE
(
    RespondentID BIGINT NOT NULL,
    Andorra VARCHAR(25),
    Austria VARCHAR(25),
    Belgium VARCHAR(25),
    Cyprus VARCHAR(25),
    Denmark VARCHAR(25),
    Finland VARCHAR(25),
    France VARCHAR(25)
)

INSERT INTO @source 
(RespondentID, Andorra,   Austria, Belgium,  Cyprus,   Denmark,    Finland,   France)
VALUES
(2546078180,   'Andorra', NULL,    NULL,     'Cyprus', NULL,       NULL,      NULL),
(2546077668,   NULL,      NULL,    'Belgium', NULL,    NULL,       NULL,      NULL),
(2546077120,   NULL,      NULL,    NULL,      NULL,    'Denkmark', 'Finland', NULL)

-- I assume that 'NULL' cell values from your Excel sheet become NULL during the import.

Output:

RespondentId         Country
-------------------- -------------------------
2546078180           Andorra
2546078180           Cyprus
2546077668           Belgium
2546077120           Denkmark
2546077120           Finland

UNION clause is the way to go:

  SELECT * FROM (
    SELECT RespondentID, Field1 as Country
    FROM myTable
    UNION
    SELECT RespondentID, Field2 as Country
    FROM myTable
    UNION
    ....
    UNION
    SELECT RespondentID, Fieldn as Country
    FROM myTable) t
  WHERE Country IS NOT NULL
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!