[英]Query to return column values as comma separated - postgresql
我在我的应用程序中使用物化视图。
查询如下
SELECT
DISTINCT n.order_id,
CASE
WHEN n.customer_billing = TRUE THEN 'AR (Customer Billing)'
WHEN n.commander = TRUE THEN 'AP (Commander)'
WHEN n.agent = TRUE THEN 'AP (Agent)'
ELSE NULL
END AS finance
FROM
pt.notes n
WHERE
n.order_id = 891090 AND
(n.customer_billing = TRUE or n.commander = TRUE or n.agent = TRUE)
这会产生以下 output
财务列的 output 应该是逗号分隔值,而不是两条记录。
也就是output应该是
AP(代理)、AR(客户账单)
我知道聚合函数可以在这里使用,但不确定当查询有 switch cases 和所有时如何使用。
关于如何实现这一目标的任何想法?
考虑一下:在数据库查询中以这种方式对数据进行反规范化很少是明智的; 最好在 UI 中完成。 但是,如果这直接进入汇总报告; 在这里这样做可能是有意义的……但是请记住,如果以后需要将其分开; 您最好在 UI 中进行合并。
笔记:
string_Agg()
function 然后“Case”语句被包装在 string_agg() function 中,因为我们像数学一样从里到外操作,所以首先解决了 case。GROUP BY
DISTINCT
,因为GROUP BY
会处理它,因此 distinct 是不需要的混乱。FROM
子句更正为您的子句有关此的更多信息--> 如何连接 postgresql 中字符串字段的字符串
WITH notes AS (
SELECT 891090 Order_ID, False customer_billing, false commander, true agent UNION ALL
SELECT 891090, true, false, false UNION ALL
SELECT 891091, false, true, false UNION ALL
SELECT 891091, true, false, false)
SELECT
n.order_id,
string_Agg(CASE
WHEN n.customer_billing = TRUE THEN 'AR (Customer Billing)'
WHEN n.commander = TRUE THEN 'AP (Commander)'
WHEN n.agent = TRUE THEN 'AP (Agent)'
ELSE NULL
END,', ') AS finance
FROM notes n
WHERE
n.order_id = 891090 AND
(n.customer_billing = TRUE or n.commander = TRUE or n.agent = TRUE)
GROUP BY ORDER_ID
给我们:
+----------+---------------------------------------+
| order_id | finance |
+----------+---------------------------------------+
| 891091 | AP (Commander), AR (Customer Billing) |
| 891090 | AP (Agent), AR (Customer Billing) |
+----------+---------------------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.