首页 > 解决方案 > 如何将 Pivot 的结果保存到公用表表达式?

问题描述

我写了这个查询,内部工作正常,但是当我尝试运行'with'行时,我得到:

消息 102,级别 15,状态 1,第 14 行 ')' 附近的语法不正确。

with Cheese as(
    select * from (
        Select a.ID,c.Data,c.Name
        from Account as a
        Left join AccountContacts AS ac on ac.AccountID=a.ID
        left join Contact AS c on ac.AccountID=c.ID
        where a.ID in(30176)
    ) as d
    pivot (max(d.Data) for d.Name in ([email],[phone])) as p
    where p.email is not null or p.phone is not null
)

这必须是一个语法错误,但我只是没有看到它。我错过了什么?

标签: sqlsql-server

解决方案


创建 CTE 时,必须在以下表达式中使用它。因此,只需在右括号后的末尾添加以下行。

SELECT * FROM cheese

推荐阅读