SQL 查询在 Azure SQL 数据仓库 (Synapse) 中不起作用,为什么不呢?

问题描述

我有一个可在本地 sql 数据库中运行的 sql 查询,但是当我尝试在 Azure sql 数据仓库上执行它时,出现错误。 有谁知道编写此 sql 查询的另一种方法,以便它可以在 Azure DW 中使用?

sql 查询是:

SELECT MAX(Dates) MostRecentDate FROM (VALUES('2020-01-01'),('2021-01-01')) AS t(Dates)

Azure DW 错误是:

消息 103010,级别 16,状态 1,第 1 行 第 1 行解析错误,第 39 列:“(”附近的语法不正确。

这里是完整的SQL查询(真实的表名已被删除

SELECT t1.reference,dd.closest_date,d1.date_one,d2.date_two,d3.date_three
FROM dbo.table1 AS t1
LEFT JOIN dbo.table2 AS t2 ON t1.table2_id = t2.id
LEFT JOIN dbo.table3 AS t3 ON t1.table3_id = t3.id
LEFT JOIN dbo.table4 AS t4 ON t3.table4_id = t4.id
LEFT JOIN dbo.table5 AS t5 ON t4.table5_id = t5.id
LEFT JOIN dbo.table6 AS t6 ON t5.table6_id = t6.id
OUTER APPLY (SELECT CASE WHEN t3.outcome IS NULL THEN '5000-01-01' ELSE ISNULL(t3.outcome_date,'5000-01-01') END AS date_one) AS d1
OUTER APPLY (SELECT ISNULL(t2.outcome_date,'5000-01-01') AS date_two) AS d2
OUTER APPLY (SELECT ISNULL(t6.outcome_date,'5000-01-01') AS date_three) AS d3
/*the below works in normal sql,but doesn't work in Azure sql!!!*/
--  OUTER APPLY (SELECT MIN(Dates) closest_date FROM (VALUES(d1.date_one),(d2.date_two),(d3.date_three)) AS t(Dates)) AS dd

解决方法

Table Value Constructor 很好,但根据文档,Azure Synapse Analytics 不完全支持,即链接文档顶部的适用于列表中没有 Synapse。根据 this example,单行支持 VALUES,但对于您的示例,最简单的解决方法是简单地将其重写为简单的 UNION ALL 语句,例如

SELECT t1.reference,dd.closest_date,d1.date_one,d2.date_two,d3.date_three
FROM dbo.table1 AS t1
    LEFT JOIN dbo.table2 AS t2 ON t1.table2_id = t2.id
    LEFT JOIN dbo.table3 AS t3 ON t1.table3_id = t3.id
    LEFT JOIN dbo.table4 AS t4 ON t3.table4_id = t4.id
    LEFT JOIN dbo.table5 AS t5 ON t4.table5_id = t5.id
    LEFT JOIN dbo.table6 AS t6 ON t5.table6_id = t6.id
    OUTER APPLY (SELECT CASE WHEN t3.outcome IS NULL THEN '5000-01-01' ELSE ISNULL(t3.outcome_date,'5000-01-01') END AS date_one) AS d1
    OUTER APPLY (SELECT ISNULL(t2.outcome_date,'5000-01-01') AS date_two) AS d2
    OUTER APPLY (SELECT ISNULL(t6.outcome_date,'5000-01-01') AS date_three) AS d3

/*the below works in normal SQL,but doesn't work in Azure Synapse*/
    --OUTER APPLY (SELECT MIN(Dates) closest_date FROM (VALUES(d1.date_one),(d2.date_two),(d3.date_three)) AS t(Dates)) AS dd
    OUTER APPLY (SELECT MIN(Dates) closest_date FROM ( SELECT d1.date_one UNION ALL SELECT d2.date_two UNION ALL SELECT d3.date_three) AS t(Dates)) AS dd

这真的只是语法糖。它们都是在一天结束时设置的操作。

,

你可以试试这个吗

 select max(t.dates)from
  (
      select '2020-01-01'as dates
        union all
      select '2021-01-01'
  )as t