SUM查询...再次遇到麻烦

时间:2012-09-17 13:36:53

标签: sql

所以我之前问过这样的问题,我想我只是不明白答案(尽管答案有效)将答案输入下一个问题

轻松查询。我拉着员工,约会,总计。超出时间卡计划PER员工。我正在寻找的是totalhrs colum的总和,但也显示所有提交的时间卡。所以我现在使用的代码

 SELECT date,totalhrs,SUM(totalhrs) 
 FROM tcardsubmit 
 WHERE employee= 'employee name' 
 ORDER BY date

此代码显示

|EMPLOYEE | DATE        | TOTALHRS | SUM(TOTALHRS)
| myname  | myfirstdate |     5    |     10

我希望它显示的是特定员工输入的所有时间卡。不仅仅是一个链接。所以在'myname'中我会有3个时间卡,其中SUM确实等于本周提交的10个小时。总和适用于数学。我似乎无法显示员工输入的所有时间卡。这就是我希望它看起来像

|EMPLOYEE | DATE         | TOTALHRS | SUM(TOTALHRS)
| myname  | myfirstdate  |     5    |     10
| myname  | myseconddate |     4    |     10
| myname  | mythirddate  |     1    |     10

3 个答案:

答案 0 :(得分:2)

测试一下,看看这是否适合你:

SELECT 
    date, 
    totalhrs, 
    (SELECT SUM(b.totalhrs) FROM tcardsubmit b WHERE b.employee = a.employee) AS totalhrs_sum 
FROM 
    tcardsubmit a 
WHERE 
    employee = 'employee name' 
ORDER BY 
    date 

说明对于子选择中的where子句: 在子选择WHERE子句中,我们检查只获取与主选择员工具有相同员工的记录(b.employee = a.employee),因此SUM(b.totalhrs)将只是员工记录的总和你得到他的记录。在主要选择中我们说FROM tcardsubmit a所以我们命名主tcardsubmit a并且在sub select中我们命名表b以避免因使用相同的表和字段名称而产生任何冲突。

答案 1 :(得分:0)

在这种情况下,除了要撤回的正常行之外,还需要使用子查询来获取总小时数:

SELECT 
    date,
    totalhrs,
    (
    select 
        sum(a.totalhrs) 
    from 
        tcardsubmit a 
    where 
        a.employee=employee
    ) as TotalHrs
FROM 
    tcardsubmit 
WHERE 
    employee= 'employee name' 
ORDER BY 
    date

答案 2 :(得分:0)

SELECT tcardsubmit.employee, date,tcardsubmit.totalhrs, SumTotal.totalhrs
FROM tcardsubmit 
WHERE employee= 'employee name' 
inner join ( Select Employee, Sum(totalhrs) as TotalHrs From tcardSubmit Group By Employee) as sumTotal
On Sumtotal.employee = tcardsubmit.employee
ORDER BY date

如果你想要一个聚合(最小值,最大值,总和等)和细节,那么就可以进行连接了。

如果你有两个同名的员工,你打算做什么呢?