sql - 根据其他列中存在的数据修改列的内容
问题描述
我拥有的数据如下所示 -
category_id category Type_1 Type_2 no_of_items
123 cat_A A both 5
123 cat_A B both 10
123 cat_B B both 35
123 cat_B A both 10
123 cat_C A both 20
我想达到以下结果-
当 category_id 时,category 为 SAME,Type_2 为“both”(Type_2 中还有很多其他类型)-
检查 Type_1 是否有 A 和 B 的记录,如果有,则将 Type_1 更改为“两者”,否则保持原样并将no_of_items 相加。
如果 Type_1 有 A 或 B 的记录,则保持 Type_1 原样。
结果应该看起来像 -
category_id category Type_1 Type_2 no_of_items
123 cat_A both both 15
123 cat_B both both 45
123 cat_C A both 20
解决方案
如果我让你正确,那么下面的查询将通过sum(no_of_items)
. 这是 postgres 中的演示,但同样的解决方案应该适用于 BigQuery。
select
category_id,
category,
case when total = 2 then 'both' else Type_1 end as Type_1,
Type_2,
sum(no_of_items) as no_of_items
from
(select
category_id,
category,
Type_1,
Type_2,
no_of_items,
count(Type_1) over (partition by category) as total
from category
) t
group by
category_id,
category,
case when total = 2 then 'both' else Type_1 end,
Type_2
order by
category
输出:
----------------------------------------------------
category_id category type_1 type_2 no_of_items
----------------------------------------------------
123 cat_A both both 15
123 cat_B both both 45
推荐阅读
- docker - 如何在本地主机上保存来自 docker 容器的数据?
- php - 如何修复“PHP 警告:ftp_login():登录验证失败”
- reactjs - 由于 CORS,Axios 无法从 s3 下载图像
- firemonkey - iOS 上的屏幕方向
- configuration - 添加 python 支持以从 cgi-bin 读取后,lighttpd 守护程序无法启动
- linq - 将 Linq 列与最小值列连接
- python - 在另一个方法中创建方法
- python - 无法在 Python 中捕获 ValueError
- c++ - 发送和十六进制消息时套接字代码 C++ 的问题
- react-native - React Navigation 抽屉不显示当前页面的标题