0

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

轻松查询。我正在拉员工,日期,totalhrs。每个员工的考勤卡计划之外。我正在寻找的是 totalhrs 列的总和,还要显示所有提交的考勤卡。所以我现在使用的代码

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

此代码显示

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

我希望它显示的是特定员工输入的所有考勤卡。不只是一个链接。因此,在“我的名字”中,我将有 3 个时间卡,其中 SUM 实际上等于一周提交的 10 小时。总和适用于数学。我似乎无法让它显示员工输入的所有考勤卡。这是我想要的样子

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

3 回答 3

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,在子选择中,我们将表命名为 b,以避免由于使用相同的表和字段名称而产生任何冲突。

于 2012-09-17T13:41:14.037 回答
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

如果您想要一个聚合(Min、Max、sum 等)和详细信息,那么连接就是要走的路。

PS如果你有两个同名的员工你会怎么做!

于 2012-09-17T13:47:16.190 回答
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
于 2012-09-17T13:39:19.950 回答