我在我的應用程式中使用物化視圖。
查詢如下
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)
這會產生以下輸出

財務列的輸出應該是逗號分隔值,而不是兩條記錄。
那就是輸出應該是
AP(代理)、AR(客戶計費)
我知道可以在這里使用聚合函式,但不確定當查詢有切換案例時如何使用。
關于如何實作這一目標的任何想法?
uj5u.com熱心網友回復:
考慮一下:在資料庫查詢中以這種方式對資料進行反規范化很少是明智的;在 UI 中做得更好。但是,如果這直接進入匯總報告;在這里這樣做可能很有意義......但請記住,如果以后需要將其分開;你最好在 UI 中進行合并。
筆記:
- 將 case 包裹在
string_Agg()函式中,然后將“Case”陳述句包裹在 string_agg() 函式中,并且由于我們像數學一樣從內到外進行操作,因此首先解決了 case。 GROUP BY為非聚合元素添加- 消除
DISTINCT因為GROUP BY照顧它如此獨特是不必要的混亂。 - 添加了額外的示例資料以顯示如何處理多個列。
- 消除了 pt.notes 表,因為我沒有在生成的公用表運算式中使用它
- 您將不需要“with notes as ()...”只需在其后選擇并將子句更正
FROM為您的子句
dbfiddle.uk 示例
有關此的更多資訊-->如何在 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) |
---------- ---------------------------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432609.html
標籤:sql PostgreSQL
