[Postgres] Subquery Dynamic Datasets in SQL

SQL is dynamic enough to handle queries within queries. These inner queries are called subqueries and they can be used in many different sections of another query. In this video we will use subqueries within a where clause, a join statement, and as a column value.

 

$ postgres=# select create_date, first_name from Users where create_date = (select min(create_date) from Users);

     min     | first_name
 ------------+------------
  2018-06-06 | tyler 
(1 row)

 

$ postgres=# select total, first_name from Users us inner join (select count(user_handle) as total, user_handle from Purchases group by user_handle) p on p.user_handle = us.user_handle;
   total     | first_name
 ------------+------------
         1   | danny 
         2   | mary 
(2 rows)

 

$ postgres=# select user_handle, sku, (select avg(quantity) from Purchases) from Purchases;
              user_handle             |                sku                    |       avg
--------------------------------------+---------------------------------------+--------------- 
 6ab3b2d2-8e02-890c-bb6d-61a67cd43f31 | 2839f831-f82c-faj3-aof3-fj28ddks39ek  | 1.50000000000
 a0eebc99-9c0b-42f8-g3eh-6bb9bd380a11 | a0eebc99-9c0b-42f8-bb6d-6bb9bd380a11  | 1.50000000000
 2839f831-f82c-faj3-aof3-fj28ddks39ek | a0eebc99-9c0b-42f8-bb6d-6bb9bd380a11  | 1.50000000000
 a0eebc99-9c0b-42f8-g3eh-6bb9bd380a11 | 2839f831-f82c-faj3-aof3-fj28ddks39ek  | 1.50000000000
(4 rows)

 

select user_handle, sku, (select avg(quantity) from Purchases where user_handle = p.user_handle and sku = p.sku) from Purchases p group by user_handle, sku;

 

posted @   Zhentiw  阅读(171)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-09-07 [D3] Add hovercard
2017-09-07 [D3] Add label text
2017-09-07 [D3] Add image to the node
2016-09-07 [Javascript] Maybe Functor
2015-09-07 [Flux] 3. Actions
2015-09-07 [RxJS] Aggregating Streams With Reduce And Scan using RxJS
2015-09-07 [RxJS] map vs flatMap
点击右上角即可分享
微信分享提示