从两个表中选择数据加入

时间:2015-09-23 04:09:25

标签: sql sql-server

这些是表:dbo.applicationdbo.actiondbo.ogpo_deptdbo.employees

| ID | dept_id | action | premium |    | ID | Name     |    
------------------------------------    -----------------      
| 1  | 5       | 21     | 61446   |    | 21 | Stiker   |    
| 2  | 11      | 18     | 325     |    | 18 | One Super|
| 3  | 5       | null   | 224     |
| 4  | 11      | 18     | 262     |

| ID | Name               |            | ID | FullName | dept_id |
---------------------------            ---------------------------
| 5  | Sales Dep          |            | 1  | Mike     | 5       |
| 11 | HR Dep             |            | 2  | Ronaldo  | 11      |

我的查询:

select od.name as dept_name,
       e.Fullname,
       oac.name,
       COUNT(oa.id) as total, 
       SUM(oa.premium) as premSum
from dbo.ogpo_dept od
     inner join dbo.employees e on e.dept_id = od.id
     left join dbo.application oa on oa.dept_id = od.id
     left join dbo.action oac on oac.id = oa.[action]
group by dept_name, e.Fullname, oac.name, oa.[action]

查询执行了很长时间(没有完成)。

我试过了,如果删除已执行的SUM (premium) as premSum

我想收到这样的结果:

| Dept_name | FullName | Name     | total | premium |
-----------------------------------------------------
| Sales Dep | Mike     |One Super |68     | 40210   |
| HR Dep    | Ronaldo  |NULL      | 0     | Null    |

1 个答案:

答案 0 :(得分:-2)

SELECT od.NAME AS dept_name
    ,e.Fullname
    ,oac.NAME
    ,COUNT(oa.id) AS total
    ,SUM(oa.premium) AS premSum
FROM dbo.ogpo_dept WITH (NOLOCK) od
INNER JOIN dbo.employees WITH (NOLOCK) e ON e.dept_id = od.id
LEFT JOIN dbo.application WITH (NOLOCK) oa ON oa.dept_id = od.id
LEFT JOIN dbo.action WITH (NOLOCK) oac ON oac.id = oa.[action]
GROUP BY dept_name
    ,e.Fullname
    ,oac.NAME
    ,oa.[action]