简体   繁体   English

如何在 SQL 的单列中显示多列?

[英]How to show multiple columns in a single column in SQL?

I have a table attendee, when joining table attendee with table Session, attendee can attend many sessions.我有一个表参加者,当加入表参加者与表 Session 时,参加者可以参加许多会议。 So when showing the attendees and what sessions they attended, I am getting multiple rows of the same Attendee, example:因此,当显示与会者以及他们参加了哪些会议时,我会得到多行相同的与会者,例如:

John Doe-BMW Conference
John Doe-Blockchain conference
Jane Doe-blabla
John Doe- Mercedess

Is there a way in sql to display sql 有没有办法显示

John Doe- BMW Conference,Mercedes,Block chain? John Doe-宝马会议,梅赛德斯,区块链?

SELECT Distinct
  attendee.Id, attendee.Firstname, attendee.PhoneNumber,
  attendee.Email,attendee.Town, attendee.BloodType, session.Id ,
  session.LocationId , session.Name as SessionName , location.Id ,
  location.Name as Location_Name , sessionattended.SessionAttendedId,
  sessionattended.SessionId, sessionattended.AttendeeId,
  attendee.Lastname
FROM `session`, `attendee`, `sessionattended`, `location`
WHERE attendee.Id = sessionattended.AttendeeId 
  and session.Id = sessionattended.SessionId 
  and session.LocationId = location.Id;

use GROUP_CONCAT MySQL (available since a long time)使用 GROUP_CONCAT MySQL (很久以来可用)

or STRING_AGG MSSQL (available in version 2017 and later)或 STRING_AGG MSSQL (在 2017 及更高版本中可用)

for a comparison of both, see: https://database.guide/mysql-group_concat-vs-t-sql-string_agg/有关两者的比较,请参阅: https://database.guide/mysql-group_concat-vs-t-sql-string_agg/

Google will find info on how to do this in other DBMS's, or even how to do it 'the old way', like here: GROUP BY to combine/concat a column谷歌将在其他 DBMS 中找到有关如何执行此操作的信息,甚至可以找到如何以“旧方式”执行此操作的信息,例如: GROUP BY to combine/concat a column

Try this.尝试这个。 Basically the idea is to use FOR XML PATH for this type of result.基本上这个想法是使用 FOR XML PATH 来获得这种类型的结果。

SELECT Distinct
       a.Id, a.Firstname, a.PhoneNumber, a.Email,a.Town, a.BloodType, 
       all_conferences = STUFF((SELECT ',' + CAST(s1.Name as Varchar) 
                                FROM sessionattended sa1  
                                JOIN Session s1 ON sa1.SessionId = s1.Id
                                WHERE sa1.AttendeeId = sa.AttendeeId FOR XML PATH('') ), 1, 1, '')

FROM `session` s
JOIN `sessionattended` sa ON sa.SessionId = s.Id
JOIN `attendee` a ON a.Id = sa.AttendeeId 
JOIN `location` l ON s.LocationId = l.Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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