Return multiple values in one column within a main query

后端 未结 2 2036
感情败类
感情败类 2021-01-15 23:35

I am trying to find Relative information from a table and return those results (along with other unrelated results) in one row as part of a larger query.

I already t

相关标签:
2条回答
  • 2021-01-16 00:02

    I think you need something like this (SQL Server):

      SELECT stuff((select ',' +Relation 
      FROM tblNextOfKin a
      WHERE ID ='xxx' AND Address ='yyy'  
      ORDER BY Relation
      FOR XML path('')),1,1,'') AS res;
    
    0 讨论(0)
  • 2021-01-16 00:03

    Mysql has GROUP_CONCAT

    SELECT GROUP_CONCAT(Relation ORDER BY Relation SEPARATOR ', ') AS item  
    FROM tblNextOfKin  
    WHERE ID ='xxx' AND Address ='yyy' 
    

    You can do it for the whole table with

    SELECT ID, Address, GROUP_CONCAT(Relation ORDER BY Relation SEPARATOR ', ') AS item  
    FROM tblNextOfKin  
    GROUP BY ID, Address 
    

    (assuming ID is not unique)

    note: this is usually bad practice as an intermediate step, this is acceptable only as final formatting for presentation (otherwise you will end up ungrouping it which will be pain)

    0 讨论(0)
提交回复
热议问题