【问题标题】:Sum function in sql querysql查询中的求和函数
【发布时间】:2016-09-23 19:28:28
【问题描述】:

我有这张桌子Student

  1. Id(int,主键标识)
  2. 名称 (varchar(20))
  3. 分数(整数)
  4. 记录日期(日期时间)

我需要根据学生的Name 选择此表的所有列以及代表“分数”列的“总和”的额外列。

我试过了,但是没用

select S.Id,S.Name ,S.Score ,S.RecordDate, ( select Sum(Score) from Student where Name= S.Name) as All_Student_Score
 from Student S;

如何更改此查询?

【问题讨论】:

  • 不要混淆数据库
  • 你是在 SQL-Server 还是 mysql 中寻找这个?
  • @KannanKandasamy 两个

标签: sql aggregate-functions


【解决方案1】:
You can use a `JOIN`:

    SELECT S.*,
           T.All_Student_Score
    FROM Student S
    INNER JOIN (SELECT Name, SUM(Score) All_Student_Score
                FROM Student) T
        ON S.Name = T.Name;

【讨论】:

    【解决方案2】:

    你可以这样试试

    select Id,Name ,Score ,RecordDate, sum(score) over(partition by name) as All_Student_Score from Student S
    

    【讨论】:

    • 你是对的,没有注意到。但是您的查询仍然是错误的
    • 只是注意到他在询问个人姓名的总和。谢谢,因为他提到的别名是“All_student_score”,所以我很困惑......
    【解决方案3】:

    以下解决方案可满足您的要求。

    select Id, 
           Name,
           Score,
           RecordDate,
           sum(score) over( partition by name ) as All_Student_Score 
      from Student; 
    

    【讨论】:

      【解决方案4】:

      因为没有人告诉您,如果您只是在子查询中为您的表设置别名,那么您自己的解决方案应该可以工作,您可以执行以下操作:

      select
           S.Id,S.Name
           ,S.Score
           ,S.RecordDate
           ,(select Sum(Score) from Student s2 where s2.Name= S.Name) as All_Student_Score
      from
           Student S;
      

      【讨论】:

        猜你喜欢
        • 2013-06-17
        • 1970-01-01
        • 2015-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-28
        相关资源
        最近更新 更多