[英]Query to return column values as comma separated - postgresql
I am using materialized view in my application.我在我的应用程序中使用物化视图。
The query is as follows查询如下
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)
This produces the following output这会产生以下 output
Instead of two records, the output of finance column should be comma separated values.财务列的 output 应该是逗号分隔值,而不是两条记录。
That is the output should be也就是output应该是
AP (Agent), AR (Customer Billing) AP(代理)、AR(客户账单)
I know aggregate functions can be used here, but not sure how to use when the query has switch cases and all.我知道聚合函数可以在这里使用,但不确定当查询有 switch cases 和所有时如何使用。
Any idea on how to achieve this?关于如何实现这一目标的任何想法?
Consider: Seldom is it wise to de-normalize data this way in the database query;考虑一下:在数据库查询中以这种方式对数据进行反规范化很少是明智的; Better done in UI.
最好在 UI 中完成。 However, if this is going directly to an aggregated report;
但是,如果这直接进入汇总报告; it may make sense to do it here... But keep in mind if this ever will need to be separated later;
在这里这样做可能是有意义的……但是请记住,如果以后需要将其分开; you're better off doing the combine in the UI.
您最好在 UI 中进行合并。
Notes:笔记:
string_Agg()
function the "Case" statement is then wrapped in the string_agg() function and since we operate inside out just like math, the case is resolved 1st. string_Agg()
function 然后“Case”语句被包装在 string_agg() function 中,因为我们像数学一样从里到外操作,所以首先解决了 case。GROUP BY
for non-aggregated element(s)GROUP BY
DISTINCT
as GROUP BY
takes care of it so distinct is unneeded clutter.DISTINCT
,因为GROUP BY
会处理它,因此 distinct 是不需要的混乱。FROM
clause to yoursFROM
子句更正为您的子句dbfiddle.uk Example dbfiddle.uk 示例
More on this--> How to concatenate string of a string field in postgresql有关此的更多信息--> 如何连接 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
Giving us:给我们:
+----------+---------------------------------------+
| order_id | finance |
+----------+---------------------------------------+
| 891091 | AP (Commander), AR (Customer Billing) |
| 891090 | AP (Agent), AR (Customer Billing) |
+----------+---------------------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.