如何在一个查询中检索总和

时间:2014-12-20 17:37:35

标签: sql sql-server

以下是表格的简要说明:

所以每个人都有工作,每个工作都有时钟和时钟,而且,每个工作都有不同的工资率,我需要检索每个工作工资的总和,基本上是小时数*支付,然后再次总结结果,因为每小时的工资率是不同的。

这是我提出的,但它给了我3列,因为我按小时工资分组:

SELECT SUM(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) AS [Minutes]
      ,CAST(ROUND(SUM(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) 
           / 60.0 * dbo.tbl_Jobs.job_hourly_pay, 2) AS numeric(36, 2)) AS Total_P
      ,CAST(ROUND(AVG(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) 
          / 60.0 * dbo.tbl_Jobs.job_hourly_pay, 2) AS numeric(36, 2)) AS Avg_Pay

FROM dbo.tbl_Jobs 
INNER JOIN dbo.tbl_Clock  ON dbo.tbl_Jobs.user_id = dbo.tbl_Clock.user_id 
                         AND dbo.tbl_Jobs.job_id = dbo.tbl_Clock.job_id
WHERE (dbo.tbl_Jobs.user_id = 111) 
  AND (DATEPART(m, GETDATE()) = DATEPART(m, dbo.tbl_Clock.clock_in))
  AND (DATEPART(yyyy, GETDATE()) = DATEPART(yyyy, dbo.tbl_Clock.clock_in))
GROUP BY dbo.tbl_Jobs.job_hourly_pay

那么如果没有分组并基本上得到总和,怎么能这样做呢?通常我会在我看来做一个未经推荐的解决方案,即将其拆分为此查询的视图和另一个查询来总结它们。

这就是我得到的:

+--------+---------+---------+
| Minuts | Total_P | Avg_Pay |
+--------+---------+---------+
|     30 | 5.15    | 1.72    |
|    480 | 3601.60 | 3601.60 |
+--------+---------+---------+

这就是我想要的:

+--------+---------+---------+
| Minuts | Total_P | Avg_Pay |
+--------+---------+---------+
|    510 | 3606.75 | 3603.32 |
+--------+---------+---------+

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方式:

select
sum(a.Minutes)
,sum(a.Total_P)
,sum(a.Avg_Pay)
from
(
SELECT SUM(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) AS [Minutes]
      ,CAST(ROUND(SUM(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) 
           / 60.0 * dbo.tbl_Jobs.job_hourly_pay, 2) AS numeric(36, 2)) AS Total_P
      ,CAST(ROUND(AVG(DATEDIFF(mi, dbo.tbl_Clock.clock_in, dbo.tbl_Clock.clock_out)) 
          / 60.0 * dbo.tbl_Jobs.job_hourly_pay, 2) AS numeric(36, 2)) AS Avg_Pay

FROM dbo.tbl_Jobs 
INNER JOIN dbo.tbl_Clock  ON dbo.tbl_Jobs.user_id = dbo.tbl_Clock.user_id 
                         AND dbo.tbl_Jobs.job_id = dbo.tbl_Clock.job_id
WHERE (dbo.tbl_Jobs.user_id = 111) 
  AND (DATEPART(m, GETDATE()) = DATEPART(m, dbo.tbl_Clock.clock_in))
  AND (DATEPART(yyyy, GETDATE()) = DATEPART(yyyy, dbo.tbl_Clock.clock_in))
GROUP BY dbo.tbl_Jobs.job_hourly_pay
)a