sql - 在 PG Admin PostgreSQL 中合并 CASE 语句中的相似行
问题描述
我的查询需要帮助。我有这个查询
SELECT DISTINCT("Fruits"), "Apple", "Orange", "Grapes",
(SELECT (CASE WHEN "Apple" = TRUE
AND (("Orange" = TRUE OR "Orange" = FALSE OR "Orange" is NULL )
OR ("Grapes" = TRUE OR "Grapes" = FALSE OR "Grapes" is NULL)) THEN ('1')
ELSE (0)
END) as "Market A"),
(SELECT (CASE WHEN ("Apple" = FALSE OR "Apple" is NULL)
AND (("Orange" = TRUE)
AND ("Grapes" = FALSE OR "Grapes" is NULL)) THEN ('1')
ELSE (0)
END) as "Market B"),
(SELECT (CASE WHEN ("Apple" = FALSE OR "Apple" is NULL)
AND (("Orange" = TRUE)
AND ("Grapes" = TRUE )) THEN ('1')
ELSE (0)
END) as "Market C")
FROM market
WHERE "Fresh" = TRUE
GROUP BY "Fruits", "Apple", "Orange", "Grapes"
这是我得到的结果
-------------------------------------------------------------------
Market | Apple | Orange | Grapes | Market A | Market B | Market C |
-------------------------------------------------------------------
Basket A | true | true | true | 1 | 0 | 0 |
Basket A | true | true | null | 1 | 0 | 0 |
Basket B | null | null | null | 0 | 0 | 0 |
Basket A | true | null | null | 1 | 0 | 0 |
Basket A | null | true | null | 0 | 1 | 0 |
Basket C | null | true | null | 0 | 1 | 0 |
我想要下表中的结果。寻求有关如何组合相似行并计算它们的帮助?非常感谢您的帮助并非常感谢。只是做一些查询的新手。
------------------------------------------------------------------
Market | Market A | Market B | Market C |
-------------------------------------------------------------------
Basket A | 3 | 0 | 0 |
Basket A | 0 | 1 | 0 |
Basket C | 0 | 1 | 0 |
解决方案
看来您正在寻找条件聚合:
select m.market, -- not sure where this comes from
count(*) filter (where "Apple" = true) as "Market A",
count(*) filter (where coalesce("Apple", false) = false
and "Orange"
and coalesce("Grape", false) = false) as "Market B",
count(*) filter (where coalesce("Apple", false) = false
and "Orange" = true
and "Grapes" = true) as "Market C"
from market m
where "Fresh" = true
group by m.market;
请注意,我删除了条件("Orange" = TRUE OR "Orange" = FALSE OR "Orange" is NULL )
,("Grapes" = TRUE OR "Grapes" = FALSE OR "Grapes" is NULL)
因为两者始终为真,并且不会改变您的条件的结果。
我不清楚market
您想要的输出中的列是否不是表格的列。
推荐阅读
- solr - 删除 Solr 中在其他文档中出现超过 X 次的字符串
- markdown - 来自 Hugo 的图像未显示在 GitHub 页面上
- sharepoint - 如何在 Sharepoint Online 中自定义搜索框
- javascript - 使用 JQuery 洗牌表的列
- swift - 应用程序仅在 iOS 13 上崩溃:“必须返回 MPRemoteCommandHandlerStatus 或将完成处理程序作为第二个参数。”
- list-comprehension - 使用python条件的列表理解中的elif
- python - Python中NxM的矩阵乘法
- sql-server - 在 SQL Sever 中提取包含多个命名空间和不同属性的 soap xml 标记值
- r - 开罗:为什么开罗不能正常工作?
- python - 如何在python中调整base64编码图像的大小