sql - 根据城市计算订单数量
问题描述
我有一个正在创建的临时表,我们会说第 1 列是 order_id,第 2 列是 user_id,第 3 列是 start_date,第 4 列是 end_date,第 5 列是城市。
order_id user_id Start_date end_date city 101 1 200001 200101 X 101 2 200101 200110 是 101 3 200110 200112 101 3 200112 200210
我想按城市计算从它移出到另一个城市的 order_ids 的数量,并在另一列中计算从另一个城市移入它的 order_ids 的数量。
我希望它以表格形式出现,如下所示:
城市 move_out_orders move_into_orders × 1 0 是的 1 1 z 0 1
解决方案
你可以做:
with
x as (
select a.city as from_city, b.city as to_city
from t a
join t b on a.order_id = b.order_id
and a.city <> b.city
and a.end_date = b.start_date
),
o (city, cnt) as (
select from_city, count(*) from x group by from_city
),
i (city, cnt) as (
select to_city, count(*) from x group by to_city
)
select
coalesce(i.city, o.city) as city,
o.cnt as moved_out_orders,
i.cnt as moved_in_orders
from i
full join o on o.city = i.city
推荐阅读
- java - 异常是 java.net.ProtocolException:无效的 HTTP 方法:PATCH
- html - 在没有浮动的情况下将元素彼此相邻定位不能正确排列在顶部
- php - 是否可以从网站自动更新“Google 我的商家”信息?
- java - 当数据库不可用但所有数据都被缓存时,防止 Hibernate / Spring 失败
- amazon-sagemaker - 如何在 AWS Sagemaker Studio 上挂载 EFS 卷
- java - JSONObject 到 ArrayList 方括号丢失
- .htaccess - 如何重定向其中包含 %something% 的 URL
- java - ns 不存在,com.mongodb.MongoCommandException
- php - Laravel 7.2 中的 RegistersUsers 特征
- python - 如何导入 excel 文件并使用 python 和 pandas 搜索特定记录?