标量子查询 - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

标量子查询

标量子查询是圆括号中的常规 SELECT 查询,仅返回一个值:带有一个列的一行。执行此查询,返回值将在外部查询中使用。如果子查询返回零行,则子查询表达式的值为 null。如果它返回多行,则 Amazon Redshift 将返回错误。子查询可引用父查询中的变量,这将在子查询的任何一次调用中充当常量。

您可在需要表达式的大部分语句中使用标量子查询。标量子查询在下列情况下是无效表达式:

  • 作为表达式的默认值

  • 在 GROUP BY 和 HAVING 子句中

示例

以下子查询计算 2008 年全年的每笔销售支付的平均价格,然后外部查询使用输出中的值来比较每个季度每笔销售的平均价格:

select qtr, avg(pricepaid) as avg_saleprice_per_qtr, (select avg(pricepaid) from sales join date on sales.dateid=date.dateid where year = 2008) as avg_saleprice_yearly from sales join date on sales.dateid=date.dateid where year = 2008 group by qtr order by qtr; qtr | avg_saleprice_per_qtr | avg_saleprice_yearly -------+-----------------------+---------------------- 1 | 647.64 | 642.28 2 | 646.86 | 642.28 3 | 636.79 | 642.28 4 | 638.26 | 642.28 (4 rows)