我有一个表,其中包含具有其属性(例如DepId和FieldId)的Lessons。我也有两个表格,分别是关于课程部门和课程字段。我需要根据DepId和FieldId计算课程每周的上课时间百分比。我的查询如下:
Select a.FieldName, b.DepName, sum(LessonWeeklyTime), ((sum(LessonWeeklyTime))*100)/(select LessonDep, sum(LessonWeeklyTime)
From Lessons
Group By LessonDep)
from Lessons l, Departments b, Fields a
Where l.LessonDep=b.DepId
And l.LessonField=a.FieldId
Group By b.DepName,a.FieldName
但是我遇到了错误:
第16层,状态1,第2行,消息116 如果未使用EXISTS引入子查询,则只能在选择列表中指定一个表达式。
感谢帮助。
答案 0 :(得分:1)
从不在FROM
子句中使用逗号。 始终使用正确的,明确的标准 JOIN
语法。毕竟是21世纪。
您应该使用窗口功能执行此操作
select f.FieldName, d.DepName, sum(LessonWeeklyTime),
(sum(LessonWeeklyTime) * 100.0 /
sum(sum(LessonWeeklyTime)) over (partition by d.depName)
from Lessons l join
Departments d
on l.LessonDep = d.DepId join
Fields f
on l.LessonField = f.FieldId
Group By d.DepName, f.FieldName
答案 1 :(得分:0)
错误消息指出,子查询中可能只有一列。尝试这种方式:
Select a.FieldName, b.DepName, sum(LessonWeeklyTime), ((sum(LessonWeeklyTime))*100)/(select sum(LessonWeeklyTime)
From Lessons
Group By LessonDep)
from Lessons l, Departments b, Fields a
Where l.LessonDep=b.DepId
And l.LessonField=a.FieldId
Group By b.DepName,a.FieldName
答案 2 :(得分:0)
检查此:
Select a.FieldName, b.DepName, sum(LessonWeeklyTime), ((sum(LessonWeeklyTime))*100)/ sum(c.LessonWeeklyTime)
from Lessons l, Departments b, Fields a ,(select LessonDep, sum(LessonWeeklyTime) LessonWeeklyTime
From Lessons
Group By LessonDep) c
Where l.LessonDep=b.DepId
And l.LessonField=a.FieldId
And l.LessonDep=c.LessonDep
Group By b.DepName,a.FieldName
答案 3 :(得分:0)
通过必要的代码从1个表中获取时间,并使用窗口函数表示百分比。它通过ID(而不是描述)进行分组/计算,以提高性能并减少由于标签/标签无效而出现错误的可能性:
WITH CTE AS( SELECT LESSONDEP, LESSONFIELD, SUM(LESSONWEEKLYTIME) AS [TIME]
FROM [LESSONS]
GROUP BY LESSONDEP, LESSONFIELD)
SELECT F.FIELDNAME, D.DEPNAME, L.[TIME], (L.[TIME]*100.0) / (SUM(L.[TIME]) OVER (PARTITION BY L.LESSONDEP) AS [PERCENTAGE]
FROM CTE L
INNER JOIN DEPARTMENTS D ON L.LESSONDEP = D.DEPID
INNER JOIN FIELDS F ON L.LESSONFIELD = F.FIELDID