交叉应用 SQL 服务器上的列。附近的语法错误)

Cross apply on columns on SQL server. Syntax error near )

我正在尝试取消透视几列,但找不到解决语法错误的方法。

')' 附近的语法不正确。

代码如下:

SELECT dates, times, locations, events
FROM mytable
CROSS APPLY 
    (VALUES ('instance1', instance1),
            ('instance2', instance2),
            ('instance3', instance3),
            ('instance4', instance4)) as Items(locations, events)

可能是因为我的 SQL 服务器版本不支持正确的值,我需要将值存储在不同的 table 中以引用它们进行交叉应用?

太棒了,我从来没有那样旋转过。我总是使用 UNPIVOT 命令。但它似乎工作得很好。不知道你的 mytable 的结构我不知道问题所在,但我猜它没有列名 instance1 到 instance4?

这是一个独立的工作示例:

select dates
      ,times
      ,locations
      ,events
from
(
    values
        ('20181225', 'noon', 'a', 'b', 'c', 'd')
       ,('20181226', 'midnight', 'e', 'f', 'g', 'h')
) mytable (dates, times, instance1, instance2, instance3, instance4)
cross apply
(
    values
        ('instance1', instance1)
       ,('instance2', instance2)
       ,('instance3', instance3)
       ,('instance4', instance4)
) as Items (locations, events);

自从使用 VALUES like that has issues in your Azure SQL Data Warehouse, switch to UNPIVOT

SELECT dates, times, locations, events
FROM mytable t
UNPIVOT (events FOR [locations] IN ([instance1],[instance2],[instance3],[instance4])) AS unpvt;

测试here