根据列中的值将单行转换为多行

Converting single row into multiple rows based on values in columns

我有一个 table,其中每条记录代表一个人,并且有许多列用于指示他们参加的事件:

CREATE TABLE EventAttendees
(
    Person VARCHAR(100),
    [Event A] VARCHAR(1),
    [Event B] VARCHAR(1),
    [Event C] VARCHAR(1)
)

INSERT INTO EventAttendees
SELECT 'John Smith','x',NULL,NULL
UNION
SELECT 'Jane Doe',NULL,'x','x'
UNION
SELECT 'Phil White','x',NULL,'x'
UNION
SELECT 'Sarah Jenkins','x','x','x'

例如,看起来像这样:

SELECT * FROM Event Attendees

/---------------|---------|---------|---------\
| Person        | Event A | Event B | Event C |
|---------------|---------|---------|---------|
| John Smith    |    x    |   NULL  |   NULL  |
| Jane Doe      |   NULL  |    x    |    x    |
| Phil White    |    x    |   NULL  |    x    |
| Sarah Jenkins |    x    |    x    |    x    |
\---------------|---------|---------|---------/

我想生成一份谁参加了哪些活动的列表,所以我想要的输出是:

/---------------|---------|
| Person        | Event   |
|---------------|---------|
| John Smith    | Event A |
| Jane Doe      | Event B |
| Jane Doe      | Event C |
| Phil White    | Event A |
| Phil White    | Event C |
| Sarah Jenkins | Event A |
| Sarah Jenkins | Event B |
| Sarah Jenkins | Event C |
\---------------|---------/

实际上我有超过 3 个事件,但以上是为了便于解释(顺便说一句,不是作业题)。由于事件将来可能会发生变化,而且我无法控制正在传递的数据,我真的需要一个动态解决方案来处理任意数量的可能事件列。

我假设我可以用 UNPIVOT 做一些事情,但我就是想不通,或者在 SO 或其他地方找到一个很好的例子来工作 - 有人可以帮忙吗?

我使用 outer apply:

select ea.person, v.EventName
from EventAttendees ea outer apply
     (values ('Event A', [Event A]),
             ('Event B', [Event B]),
             ('Event C', [Event C])
     ) v(EventName, EventFlag)
where v.EventFlag = 'x'

试试

SELECT * FROM (
    SELECT Person, CASE WHEN [Event A] = 'x' THEN 'Event A' END AS [Event] FROM EventAttendees
    UNION 
    SELECT Person, CASE WHEN [Event B] = 'x' THEN 'Event B' END AS [Event] FROM EventAttendees
    UNION 
    SELECT Person, CASE WHEN [Event C] = 'x' THEN 'Event C' END AS [Event] FROM EventAttendees
    ) AS EventAttendees
    WHERE Event is not null
    order by Person

对于动态 sql 你可以尝试这样的事情:

    DECLARE @name varchar(30)
    DECLARE @sql varchar(1000) = 'SELECT * FROM (';
    DECLARE NameCursor CURSOR
        FOR select name from sys.all_columns where object_id = (select object_id from sys.tables where name='EventAttendees') and name!='Person'
    OPEN NameCursor
    FETCH NEXT FROM NameCursor INTO @name

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @sql += 'SELECT Person, CASE WHEN [' + @name+'] = ''x'' THEN ''' + @name +''' END AS [Event] FROM EventAttendees'   
        FETCH NEXT FROM NameCursor INTO @name

        IF(@@FETCH_STATUS = 0)
        BEGIN
            SET @sql += ' UNION ';
        END

    END;
    CLOSE NameCursor;  
    DEALLOCATE NameCursor;
    SET @sql += ') AS EventAttendees
            WHERE Event is not null
            order by Person';

    execute (@sql);

你可以像你说的那样用 unpivot 来做,你只需要确保你告诉它它是为了什么事件,否则你只会得到一个 X:

CREATE TABLE #tmpEventAttendees
(
    Person VARCHAR(100),
    [Event A] VARCHAR(1),
    [Event B] VARCHAR(1),
    [Event C] VARCHAR(1)
)
INSERT INTO #tmpEventAttendees
SELECT 'John Smith','x',NULL,NULL
UNION
SELECT 'Jane Doe',NULL,'x','x'
UNION
SELECT 'Phil White','x',NULL,'x'
UNION
SELECT 'Sarah Jenkins','x','x','x'

SELECT Person, [Event]
FROM
(
  SELECT    Person                                                                                  , 
            CASE WHEN [Event A] IS NOT NULL THEN 'Event A' END AS [Event A]                             , 
            CASE WHEN [Event B] IS NOT NULL THEN 'Event B' END AS [Event B]                             ,
            CASE WHEN [Event C] IS NOT NULL THEN 'Event C' END AS [Event C]
  FROM #tmpEventAttendees
) AS cp
UNPIVOT 
(
  [Event] FOR [Events] IN ([Event A], [Event B], [Event C])
) AS up;

DROP TABLE #tmpEventAttendees

找到了我正在考虑的解决方案,但是是的,它确实需要动态 SQL 来获取相关的列名以输入 UNPIVOT:

declare @sql varchar(max)
set @sql = 
    'select Person, EventName
    from EventAttendees
    unpivot
    (
        Attended for EventName in (' + (select
                                        stuff((
                                            select ',' + QUOTENAME(c.[name])
                                            from sys.columns c
                                            join sys.objects o on c.object_id = o.object_id
                                            where o.[name] = 'EventAttendees'
                                            and c.column_id > 1
                                            order by c.[name]
                                            for xml path('')
                                        ),1,1,'') as colList) + ')
    ) unpiv
    where unpiv.Attended = ''x''
    order by Person, EventName'

exec (@sql)

在此示例中,我假设事件列从 table 中的第二列开始,但显然我可以在子查询中使用一些不同的逻辑来在必要时识别相关列.

在我的示例数据中,这给出了期望的结果:

/---------------------------\
| Person        | EventName |
|---------------|-----------|
| Jane Doe      | Event B   |
| Jane Doe      | Event C   |
| John Smith    | Event A   |
| Phil White    | Event A   |
| Phil White    | Event C   |
| Sarah Jenkins | Event A   |
| Sarah Jenkins | Event B   |
| Sarah Jenkins | Event C   |
\---------------------------/

我想我更喜欢这个而不是使用游标,尽管我还没有真正确认这两种动态方法之间存在什么性能差异(如果有的话)。

感谢大家对这个问题的帮助和建议,一如既往的感激不尽!