计算每个数据唯一的总元素

时间:2012-05-31 03:34:14

标签: sql

以下是这种情况。我创建了一个包含以下所有信息的视图

CREATE VIEW view2 AS
SELECT activity_id,
       subject_code,
       academic_period_code,
       DATEDIFF(HOUR,time_start,time_end) AS duration
FROM   activity

好的,现在我正在尝试创建一个可以生成两列的查询, 1.一个主题代码和academic_period代码连接成一列 2.第二栏包含该学期内每个科目的总持续时间

就像它一样:在academic_period 121中的CS123总共有5个小时的活动。我对第一栏很好,但我一直在想如何获得第二栏。如果我使用SUM函数,它只是总计列本身,所以我不知道如何处理它。

示例数据

Subject Code   Activity_code    Academic_Period_Code   Duration
CS123          1                 121                   2
CS123          2                 121                   3
CS123          3                 122                   2
CS123          4                 122                   2

我做了什么?]

SELECT subject_code + academic_period_code AS subject,
       (I think I have to do a subquery but I'm not sure how its suppose to work out) AS total_activity_time

FROM view2

2 个答案:

答案 0 :(得分:1)

假设SQL Server并且我理解您在寻找什么:

select
    subject_code + academic_period_code as [Type],
    sum(duration) as duration
from view2
group by
    subject_code + academic_period_code;

应该让你到达我认为你想要的地方。

答案 1 :(得分:0)

select
    subject_code + academic_period_code as subjects,
    sum(duration) as duration
from view2
group by
    subject_code, academic_period_code;