SQL汇总一组不同的行而不重复

时间:2015-12-03 19:25:19

标签: sql sql-server sql-server-2008

我有一个从两个表中选择数据的查询。但是,我想让名称只显示一次。即使是与众不同,它也会出现两次。我的查询将粘贴在下面,同时显示当前结果和所需结果。

employeetimesheets表中的数据也粘贴了与rowid'对应的数据。您可以看到它将0.25添加到一起,但是它如何在不增加额外行的情况下查询唯一ID的总和?任何帮助都非常感谢。

SELECT DISTINCT a.rowid, 
                a.employee, 
                Sum(b.value) AS TotalHours 
FROM   employees a 
       INNER JOIN employeetimesheets b 
               ON a.rowid = b.empid 
WHERE  b.title = '50001310-01' 
GROUP  BY a.rowid, 
          a.employee, 
          b.value 

当前结果

4   Aa Bus  0.5
4   Aa Bus  1.5
95  Lh Wr   7.5
95  Lh Wr   8

期望的结果

4   Aa Bus  2.0
95  Lh Wr   15.5

RowId' 4'

的EmployeetimeSheets中的数据
14579   4   2015-11-21  2015-11-18  50001310-01 F oy    0.25    2015-11-20 10:58:54.897 16  NULL    1
14580   4   2015-11-21  2015-11-19  50001310-01 F oy    0.25    2015-11-20 10:58:54.900 16  NULL    1
14785   4   2015-11-21  2015-11-21  50001310-01 F oy    1.5     2015-11-21 12:57:22.273 16  NULL    1

1 个答案:

答案 0 :(得分:1)

SELECT a.rowid,
       a.employee, 
       Sum(b.value) AS TotalHours 
FROM   employees a 
       INNER JOIN employeetimesheets b 
               ON a.rowid = b.empid 
WHERE  b.title = '50001310-01' 
GROUP  BY a.rowid, a.employee