如何在SQl服务器中的两个表中进行分组?

时间:2013-10-22 13:31:40

标签: sql-server

我有以下问题:

表#1结构:

请求表例如有2列:

Request_ID Branch_Name

1                  xx 
2                  yy
3                  xx
4                  xx
5                  yy

第二个表:Requests_Items例如具有以下列

Request_ID      Price  

1               100   
1               30
1               450
2               10
2               18

所以我希望我的结果集如下:

 Branch Name     Num_of_Requests     Total_Price 

    xx                 3               580

你能帮忙吗

4 个答案:

答案 0 :(得分:2)

select r.Branch_Name, 
       count(r.request_id) as Num_of_Requests, 
       sum(i.price) as Total_Price 
from Requests r
left join Requests_Items i on i.Request_ID = r.Request_ID  
group by r.Branch_Name

答案 1 :(得分:0)

jurgen d几乎就在那里

select      r.Request_Id, r.Branch_Name,
            COUNT(i.Price) as [Number of Requests],
            SUM(i.Price) as [Total]
from        Requests r
left join   Requests_Items i
on          r.Request_Id = i.Request_Id
group by    r.Request_Id, r.Branch_Name

答案 2 :(得分:0)

select r.Branch_Name, COUNT(ri.Request_ID) as Num_of_Requests, SUM(ri.Price) as Total_Price
from dbo.Requests r
left join dbo.Requests_Items ri
on r.Request_ID = ri.Request_ID
group by r.Branch_Name

答案 3 :(得分:0)

这是我的 [员工]表

enter image description here

这是我的部门

enter image description here

我想使用 join和group by

这样的输出

enter image description here

所以这是查询 -

select max(e.salary) as maxsalary,d.Dept from Employees e inner join DEpt d on e.DeptId=d.id group by e.DeptId,d.Dept
    enter code here