将多行分组为单行

Smi*_*ley 3 sql postgresql select group-by multiple-columns

我有下表:

|  ID  |  Description|  Shelf  |  QTY  |
----------------------------------------
|  10  | Apples      |    1    |   24  |
|  10  | Apples      |    2    |   28  |
|  10  | Apples      |    6    |   12  |
|  15  | Oranges     |    2    |   8   |
|  15  | Oranges     |    6    |   33  |
Run Code Online (Sandbox Code Playgroud)

我需要对此表进行一些更新,并将货架和数量作为一个组放在一起,如下所示:

|  ID  |  Description|    Availability    |
-------------------------------------------
|  10  | Apples      |  1-24, 2-28, 6-12  |
|  15  | Oranges     |  2-8, 6-33         |
Run Code Online (Sandbox Code Playgroud)

基本上,我们试图将货架和数量分组在一行中。这仅用于报告目的,因此我必须以这种方式显示数据。

到目前为止,我可以通过连接两列并添加破折号来显示两列:

SELECT ID, Description, Shelf || '-' || QTY AS Availability FROM tbl_Products
Run Code Online (Sandbox Code Playgroud)

要将它们拼接在一行中,我非常确定可以使用 WHILE 循环来遍历这些值并创建可用性字符串字段,然后将其插入回临时表,然后将其打印到报告中。

但我对性能不太确定。由于此查询将在一个大表中运行,我只是担心每次提取报告时它都会减慢数据库速度。

那么还有其他更简单的方法可以实现这一目标吗?

Mur*_*nik 7

string_agg完全符合要求:

SELECT   id, description, STRING_AGG(shelf || '-' || qty, ', ') AS Availability
FROM     tbl_Products
GROUP BY id, description
Run Code Online (Sandbox Code Playgroud)