我已阅读过相似的帖子,但无法让我的查询工作。
以下是我所拥有的:
SELECT u.Id,
U.FirstName as [Name],
ut.UserType,
COUNT(DISTINCT(s.rawScoreDate)) as [Total Sessions],
COUNT(DISTINCT(s.SkillId)) AS [Skills Used],
SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END) AS [Total Scores],
SUM(CASE s.score WHEN 1 THEN 1 ELSE 0 END) AS [1's Scored],
SUM(CASE s.score WHEN 2 THEN 1 ELSE 0 END) AS [2's Scored],
SUM(CASE s.score WHEN 3 THEN 1 ELSE 0 END) AS [3's Scored],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 1 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [1's %],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 2 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [2's %],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 3 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [3's %],
(SELECT SkilsName as skls FROM tblSkils as sk where sk.SkilsId=s.SkillId) as [Skills]
FROM tblUser AS u
LEFT OUTER JOIN tblRawScore AS s ON (U.Id=s.AssignedBy) JOIN tblUserType AS ut ON (u.UserTypeId=ut.Id)
WHERE u.usertypeid=4
GROUP BY u.id, u.FirstName,ut.UserType,s.SkillId
ORDER BY [Total Sessions] DESC
虽然[技能使用]仅为1,但是如果有超过1个,我认为它将返回第一个技能或结果中的重复行。
有没有办法可以将[Skills]查询的结果放入字符串中,例如:
Skill1,Skill2,Skill3
很抱歉,如果这是一个重复的问题,但我对复杂的SQL查询还不熟悉。
答案 0 :(得分:2)
STUFF((SELECT ', ' + [Skills Used]
FROM FROM tblUser AS x LEFT OUTER JOIN tblRawScore AS y ON (x.Id=y.AssignedBy)
JOIN tblUserType AS z ON (x.UserTypeId=z.Id) WHERE x.ID=u.ID FOR XML PATH('')),1,2,'')
将此作为查询中的一个字段。
答案 1 :(得分:0)
感谢jbarker,我已经成功地解决了这个问题:
SELECT u.Id,
U.FirstName as [Name],
ut.UserType,
COUNT(DISTINCT(s.rawScoreDate)) as [Total Sessions],
COUNT(DISTINCT(s.SkillId)) AS [Skills Used],
SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END) AS [Total Scores],
SUM(CASE s.score WHEN 1 THEN 1 ELSE 0 END) AS [1's Scored],
SUM(CASE s.score WHEN 2 THEN 1 ELSE 0 END) AS [2's Scored],
SUM(CASE s.score WHEN 3 THEN 1 ELSE 0 END) AS [3's Scored],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 1 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [1's %],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 2 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [2's %],
CAST(100.0/NULLIF(SUM(CASE WHEN s.score in (1, 2, 3) THEN 1 ELSE 0 END),0) * SUM(CASE s.score WHEN 3 THEN 1 ELSE 0 END) AS NUMERIC(18,2)) AS [3's %],
STUFF(( SELECT ', ' + sk.SkilsName
FROM tblskils AS sk
WHERE sk.SkilsId=s.SkillId
FOR XML PATH('')),1,2,'') AS [Skills Used]