簡體   English   中英

將postgres中的記錄分組和拆分為幾個新的列系列

[英]Group and split records in postgres into several new column series

我有以下形式的數據

-----------------------------|
6031566779420 | 25  | 163698 |
6031566779420 | 50  | 98862  |
6031566779420 | 75  | 70326  |
6031566779420 | 95  | 51156  |
6031566779420 | 100 | 43788  |
6036994077620 | 25  | 41002  |
6036994077620 | 50  | 21666  |
6036994077620 | 75  | 14604  |
6036994077620 | 95  | 11184  |
6036994077620 | 100 | 10506  |
------------------------------

並希望通過將(25、50、75、95、100)的每個系列以及相應的值視為一個新系列來創建動態數量的新列。 我正在尋找目標輸出,

--------------------------
| 25    | 163698 | 41002 |
| 50    | 98862  | 21666 |
| 75    | 70326  | 14604 |
| 95    | 51156  | 11184 |
| 100   | 43788  | 10506 |
-------------------------- 

我不確定要調用的sql / postgres操作的名稱是什么,也不確定如何實現它。 在這種情況下,數據具有2個新列,但是我試圖制定一個解決方案,該解決方案具有許多新列,就像原始查詢的輸出中的數據組一樣。

[編輯]

感謝您對array_agg的引用,這似乎會有所幫助! 我應該早先提到過這一點,但是我正在使用Redshift來報告此版本的Postgres:

PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.1007

並且它似乎還不支持此功能。

ERROR:  function array_agg(numeric) does not exist
HINT:  No function matches the given name and argument types. You may need to add explicit type casts.
Query failed
PostgreSQL said: function array_agg(numeric) does not exist
Hint: No function matches the given name and argument types. You may need to add explicit type casts.

交叉表是我應該關注的轉換類型嗎? 或者是其他東西? 再次感謝。

我在這里用過array_agg()

select idx,array_agg(val) 
from t
group by idx

這將產生如下結果:

idx array_agg      
--- -------------- 
25  {163698,41002} 
50  {98862,21666}  
75  {70326,14604}  
95  {11184,51156}  
100 {43788,10506}  

如您所見,第二列是兩個值(列idx )的數組,對應於列idx

以下選擇查詢將為您提供兩個單獨的列的結果

Method : 1

 SELECT idx
       ,col [1] col1 --First value in the array
       ,col [2] col2 --Second vlaue in the array
FROM (
    SELECT idx
        ,array_agg(val) col
    FROM t
    GROUP BY idx
    ) s

Method : 2

SELECT idx
    ,(array_agg(val)) [1] col1 --First value in the array
    ,(array_agg(val)) [2] col2 --Second vlaue in the array
FROM t
GROUP BY idx

Result:

idx col1   col2  
--- ------ ----- 
25  163698 41002 
50  98862  21666 
75  70326  14604 
95  11184  51156 
100 43788  10506 

您可以使用array_agg函數。 假設,您的列名為ABC

SELECT B, array_agg(C)
FROM table_name
GROUP BY B

將以數組形式輸出。 這與在簡單查詢中接近變量列的程度非常接近。 如果確實需要可變列,請考慮定義一個PL / pgSQL過程以將數組轉換為列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM