sql group by是重复值吗?

时间:2016-09-08 15:45:57

标签: sql sql-server

我有一个有发言人,会议,会议,电子邮件的桌子。我的目标是创建一个将会议和会话组合到一个字段中的查询,以便我们可以应用一些HTML并在我们在其他地方预览时对其进行格式化。
这里的问题是当一位发言者参加两个不同的会议并提出不同的会议时。此查询以某种方式复制来自一个会议的会话并将其应用于第二个会议:

SELECT speaker AS 'speakername', email AS 'email',
CAST(
  (SELECT conference AS 'strong',
      (SELECT session AS 'session' from speakersessions AS ds
      WHERE ds.speaker = dd.speaker
      GROUP BY session
      for xml path(''), type) AS 'sessions'
  FROM speakersessions AS ds
  WHERE ds.speaker = dd.speaker
  GROUP BY conference 
  for xml path(''), type)
AS NVARCHAR(MAX)) 
AS 'conferences'
FROM speakersessions AS dd
GROUP BY speaker, email

结果显示发言人' greg'有:

<strong>Business Planning </strong>
<sessions><session>
10 tips to fast-track
</session><session>
Hybrid planning
</session><session>
Planning on the cloud
</session><session>
The Boardroom
</session></sessions>
<strong>Reporting Analytics</strong>
<sessions><session>
10 tips to fast-track
</session><session>
Hybrid planning
</session><session>
Planning on the cloud
</session><session>
The Boardroom
</session></sessions> <br/>

(我添加了换行符) 但正如您所看到的,这不是speakeressions表所显示的内容:

Conference                   Session
Business Planning   |   10 tips to fast-track
Business Planning   |   Hybrid planning
Reporting Analytics |   Planning on the cloud
Reporting Analytics |   The Boardroom

因此报告分析的会话不会填充。这里发生了什么?

1 个答案:

答案 0 :(得分:0)

SELECT speaker AS 'speakername', email, CAST( (SELECT conference AS 'strong', (SELECT session AS 'session' from speakersessions AS part3 WHERE part3.conference = part2.conference and part3.email = part1.email GROUP BY session,conference for xml path(''), type) AS 'sessions' FROM speakersessions AS part2 WHERE part1.email = part2.email GROUP BY part2.conference for xml path(''), type) AS NVARCHAR(MAX)) AS 'conferences' FROM speakersessions AS part1 GROUP BY email, speaker
必须确保添加了会议,但它与适当的子查询相结合