在连接多个表时,在单个查询中按总和和总和获取组

时间:2017-01-30 16:32:19

标签: sql sql-server sql-server-2014

我有2张桌子,想要多笔费用的总和 对于每个员工ID,希望我的例子能更好地解释我试图实现的结果

员工表:

Emp_ID  EmpName  EmpSrname

1001    John     Wilkes
1002    Sandra   Minotaur
1003    Dante    Inferno

费用表:

Emp_ID  Expense_Name  Ammount

1001    Lunch         25
1002    Drinks        55
1003    Hotel         120
1001    Dinner        80
1001    Breakfast     20
1002    LineDancing   15
1002    Dinner        80

通过总计(午餐,早餐,晚餐)来寻找每个Emp_Id的食物费用总额

以下是预期结果:

Emp_ID  EmpName  EmpSrname  TotalFood
1001    John     Wilkes     125
1002    Sandra   Minotaur   80 

3 个答案:

答案 0 :(得分:2)

这可以通过简单的连接和一些聚合完成,但会产生不同的输出到所需的输出:

CREATE TABLE #Employee
    ([Emp_ID] int, [EmpName] varchar(6), [EmpSrname] varchar(8))
;

INSERT INTO #Employee
    ([Emp_ID], [EmpName], [EmpSrname])
VALUES
    (1001, 'John', 'Wilkes'),
    (1002, 'Sandra', 'Minotaur'),
    (1003, 'Dante', 'Inferno')
;


CREATE TABLE #Expenses
    ([Emp_ID] int, [Expense_Name] varchar(11), [Amount] int)
;

INSERT INTO #Expenses
    ([Emp_ID], [Expense_Name], [Amount])
VALUES
    (1001, 'Lunch', 25),
    (1002, 'Drinks', 55),
    (1003, 'Hotel', 120),
    (1002, 'Dinner', 80),
    (1001, 'Breakfast', 20),
    (1002, 'LineDancing', 15)
;

SELECT em.Emp_ID ,
       em.EmpName ,
       em.EmpSrname ,
       sum(ex.Amount ) Total 
FROM #Employee em INNER JOIN #Expenses ex ON ex.Emp_ID = em.Emp_ID
WHERE ex.Expense_Name IN ('Lunch','Breakfast','Dinner')
GROUP BY em.Emp_ID ,
         em.EmpName ,
         em.EmpSrname

DROP TABLE #Employee
DROP TABLE #Expenses

<强>产地:

Emp_ID  EmpName EmpSrname   Total
1001    John    Wilkes      45
1002    Sandra  Minotaur    80

答案 1 :(得分:1)

JOIN,过滤和汇总,如下所示:

select 
    e.emp_id, e.empName, e.EmpSrName, sum(x.amount) totalfood
from employee e
inner join expenses x
on e.emp_id = x.emp_id
where x.expense_name in ('Lunch','Breakfast','Dinner')
group by e.emp_id, e.empName, e.EmpSrName;

答案 2 :(得分:1)

您可以使用简单的JOINGROUP BY

执行此操作
Select  E.Emp_Id, E.EmpName, E.EmpSrname, 
        Sum(X.Ammount) As TotalFood
From    Employee    E
Join    Expenses    X   On  X.Emp_Id = E.Emp_Id
                        And X.Expense_Name In ('Breakfast', 'Lunch', 'Dinner')
Group By E.Emp_Id, E.EmpName, E.EmpSrname

注意,您想要的结果与您的数据不符。根据样本数据,这些结果应该是结果:

Emp_ID  EmpName  EmpSrname  TotalFood
1001    John     Wilkes     45
1002    Sandra   Minotaur   80