【问题标题】:Sum of a higher level aggregation更高级别聚合的总和
【发布时间】:2018-12-19 08:08:24
【问题描述】:

我在下面的代码中定义了一个表,我希望所有值的总和为 ALLDays,在本例中为 Ajan 36 和 Sam 21。我如何修改下面的查询来获得它,我是不允许使用 windows 功能。我可以通过将另一个查询按学生分组并加入两者来实现要求,但是有没有办法修改以下查询以满足要求。非常感谢任何帮助。

DECLARE @Table 
TABLE(Student varchar(50),
subject varchar(50)
,days int)

Insert into @Table
values('Ajan','English',8),('Ajan','Math',9),('Ajan','Science',7),('Ajan','English',5),('Ajan','Math',4),('Ajan','Science',3),
('Sam','English',7),('Sam','Math',6),('Sam','Science',8)


select student,subject,sum(days) as SubjectDays,'' as AllDays from @Table
group by student,subject  

【问题讨论】:

  • 我数的是 Ajan 的 36 天,而不是 34 天。
  • 是的,改变了它。

标签: sql ansi-sql


【解决方案1】:

如果您不能使用窗口函数,那么另一种选择是对学生和学科级别的天数总和使用两个单独的子查询。

select t1.student, t1.subject, t1.SubjectDays, t2.AllDays
from
(
    select student, subject, sum(days) as SubjectDays
    from @Table
    group by student, subject
) t1
inner join
(
    select student, sum(days) as AllDays
    from @Table
    group by student
) t2
    on t1.student = t2.student;

【讨论】:

  • 是的,但我需要在同一个查询中没有任何连接,这可能吗?
【解决方案2】:

也许您可以使用 CTE 来包含总和并与之相对:

DECLARE @Table 
TABLE(Student varchar(50),
subject varchar(50)
,days int)

Insert into @Table
values('Ajan','English',8),('Ajan','Math',9),('Ajan','Science',7),('Ajan','English',5),('Ajan','Math',4),('Ajan','Science',3),
('Sam','English',7),('Sam','Math',6),('Sam','Science',8);


WITH MainSummary (Student,Alldays) AS
(
	 SELECT Student,SUM([days]) as AllDays
	 FROM @Table
	 GROUP BY Student
)
SELECT 
	T.Student
	,T.[subject]
	,SUM([Days]) AS SubjectDays
	,MAX(MS.AllDays) AS AllDays
FROM @Table AS T
LEFT JOIN MainSummary AS MS ON MS.Student = T.Student
GROUP BY T.Student,T.[Subject]

【讨论】:

    【解决方案3】:

    经过更多搜索,我找到了一种无需任何连接即可满足需求的方法,

    DECLARE @Table 
    TABLE(Student varchar(50),
    subject varchar(50)
    ,days int)
    
    Insert into @Table
    values('Ajan','English',8),('Ajan','Math',9),('Ajan','Science',7),('Ajan','English',5),('Ajan','Math',4),('Ajan','Science',3),
    ('Sam','English',7),('Sam','Math',6),('Sam','Science',8);
    
    SELECT student,subject,sum(days) as SubjectDays,
        (SELECT sum(days) from  @Table b where b.Student=a.Student ) as Alldays 
        FROM @Table a
        group by student,subject  
    

    【讨论】:

    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2017-07-27
    • 1970-01-01
    • 2019-01-31
    相关资源
    最近更新 更多