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

子查询示例

以下示例说明子查询适合 SELECT 查询的不同方式。有关使用子查询的另一个示例,请参阅JOIN 示例

SELECT 列表子查询

以下示例在 SELECT 列表中包含一个子查询。此子查询是标量:它只返回一列和一个值,该值将在从外部查询返回的每个行的结果中重复。此查询将子查询计算出的 Q1SALES 值与外部查询定义的 2008 年其他两个季度(第 2 季度和第 3 季度)的销售值进行比较。

select qtr, sum(pricepaid) as qtrsales, (select sum(pricepaid) from sales join date on sales.dateid=date.dateid where qtr='1' and year=2008) as q1sales from sales join date on sales.dateid=date.dateid where qtr in('2','3') and year=2008 group by qtr order by qtr; qtr | qtrsales | q1sales -------+-------------+------------- 2 | 30560050.00 | 24742065.00 3 | 31170237.00 | 24742065.00 (2 rows)

WHERE 子句子查询

以下示例在 WHERE 子句中包含一个表子查询。此子查询生成多个行。在本示例中,行只包含一列,但表子查询可以包含多个列和行,就像任何其他表一样。

此查询查找门票销量排名前 10 位的卖家。前 10 位卖家的列表受子查询的限制,这将删除居住在设有售票点的城市的用户。可以使用不同的方式编写此查询;例如,可将子查询重新编写为主查询中的联接。

select firstname, lastname, city, max(qtysold) as maxsold from users join sales on users.userid=sales.sellerid where users.city not in(select venuecity from venue) group by firstname, lastname, city order by maxsold desc, city desc limit 10; firstname | lastname | city | maxsold -----------+-----------+----------------+--------- Noah | Guerrero | Worcester | 8 Isadora | Moss | Winooski | 8 Kieran | Harrison | Westminster | 8 Heidi | Davis | Warwick | 8 Sara | Anthony | Waco | 8 Bree | Buck | Valdez | 8 Evangeline | Sampson | Trenton | 8 Kendall | Keith | Stillwater | 8 Bertha | Bishop | Stevens Point | 8 Patricia | Anderson | South Portland | 8 (10 rows)

WITH 子句子查询

请参阅 WITH 子句