简体   繁体   中英

Combining multiple rows into single row in postgresql

I have the following query:

SELECT distinct items.matr_code,mm_nounmodmaster.noun,mm_nounmodmaster.modifier1,mm_nounmodmaster.modifier2,mm_attributemaster.attribute, mm_templateattributes.sequence, 
mm_itemvaluemaster.itemvalue, mm_itemvaluemaster.abbrvalue, mm_templateattributes.mand_ind, mm_sourcemaster.source_code
FROM mm_items items
      INNER JOIN mm_nounmodmaster ON items.nm_code = mm_nounmodmaster.nm_code 
      INNER JOIN mm_itemattributes ON items.id = mm_itemattributes.items_id
      INNER JOIN mm_itemvaluemaster ON mm_itemattributes.itemvalmaster_id = mm_itemvaluemaster.id
      INNER JOIN mm_templateattributes ON mm_itemattributes.templateattributes_id = mm_templateattributes.id
      INNER JOIN mm_attributemaster ON mm_templateattributes.attribute = mm_attributemaster.id
      INNER JOIN mm_sourcemaster ON mm_itemattributes.source = mm_sourcemaster.id
      WHERE items.matr_code='01102027001' group by items.matr_code,mm_attributemaster.attribute, mm_templateattributes.sequence, 
mm_itemvaluemaster.itemvalue, mm_itemvaluemaster.abbrvalue, mm_templateattributes.mand_ind, mm_sourcemaster.source_code,mm_nounmodmaster.noun,mm_nounmodmaster.modifier1,mm_nounmodmaster.modifier2;

which gives me:

matr_code  |noun|mod1| mod2 |  attr  |seq | i_val | a_val  |m_ind|source

01102027001|ABRA|  --  | -- |ITEM NAME|10 | EMERY | EMERY  | Y   | --
01102027001|ABRA|  --  | -- |TYPE     |20 | --    | --     | Y   | test    
01102027001|ABRA|  --  | -- |MATERIAL |30 | --    | --     | Y   | test
01102027001|ABRA|  --  | -- |SIZE,GRIT|40 | 100   | 100    | Y   | test
01102027001|ABRA|  --  | -- |DIMENSION|50 | 280mm | 280mm  | Y   | --
01102027001|ABRA|  --  | -- |ADDITIONAL|60| DRILL | DRILL  | N   | test

by the above result matr_code, noun, mod1 and mod2 are same but other fields has differed, so totally 6 rows in the above result, but need the result in single row, below I have attached image for your Ref.

结果将在单行中

Your desired result is not 1NF as you want to return a list of results within a single record (ie for a key 01102027001|ABRA|--|-- , you would want to get ITEM NAME|10 | EMERY | EMERY | Y | -- , TYPE |20 | -- | -- | Y | test , and so on). With purely relational sql queries this is hard (or even impossible) to achieve, and it isactually very very seldom desired that way.

Relational databases (and prostgresql) can deal with NON-1NF structures, eg by using nested tables or XML output. However, it's probably much easier to adapt the presentation layer such that the common part 01102027001|ABRA|--|-- is printed just once.

您可能要尝试使用DISTINCT ON (matr_code, mod1, mod2)而不是仅使用DISTINCT ,并对所有其他不同的列使用array_agg(column_name_here)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM