连接和分组依据

时间:2019-06-08 16:35:26

标签: sql group-by

这是我的数据库的模式

table emp
eid     ename   age salary
1000    Lakmal  33  90000
1001    Nadeeka 24  28000



 table works
    eid     did             percentage
    1000    Admin           40
    1000    ITSD            50
    1001    Admin           100
    1002    Academic        100
    1003    Academic        30

我想显示员工的姓名和他/她总共工作的百分比。

这就是我尝试过的

  select sum(w.pct_time) as 'Total' ,e.ename 
from emp e, works w
where w.eid = e.eid group by w.eid

这不起作用,我收到此错误

Column 'emp.ename' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

有人可以解释如何获得上述输出吗?

3 个答案:

答案 0 :(得分:0)

这可用于百分比计算

Select (Sum(pct_time)* 100 / (Select Sum(pct_time) From works)) as 'Total',
        e.ename, e.eid
  From emp e
  Join works w
    On e.eid = w.eid
 Group By e.ename, e.eid
如果所有工作人员都包含在emp表中,则使用内部联接就足够了。您似乎有所有员工,但是缺少一些标识号的工作记录。

答案 1 :(得分:0)

按如下所示纠正您的group by子句。

select sum(w.pct_time) as 'Total' ,e.ename from emp e, works w where w.eid = e.eid group by e.ename

注意:在这里,我假设名称是唯一的,因为您只需要显示enamepct_time。如果不是这样,将不会给出正确的结果,因为它将合并所有具有相同名称的员工的结果。

如果名称不是唯一的,则也可以在e.eid子句中添加group by

select sum(w.pct_time) as 'Total' ,e.ename from emp e, works w where w.eid = e.eid group by e.eid, e.ename

答案 2 :(得分:0)

这是一个完整的SQL Server示例,其中的表已转换为通用表表达式:

with [emp] (eid, ename, age, salary)
as
(
    select
        eid,     ename,   age, salary
    from
    (
        values 
            (1000 ,  ' Lakmal', 33,  90000),
            (1001 ,   'Nadeeka', 24,  28000)
    )  as result (eid,     ename,   age, salary)
),
[works] (eid, did, pct_time)
as
(
    select
        eid, did, percentage
    from
    (    
        values 
            (1000,    'Admin', 40),
            (1000,    'ITSD', 50),
            (1001,    'Admin', 100),
            (1002,    'Academic', 100),
            (1003,    'Academic', 30)
    )  as result(eid, did, percentage)
),
[grouped] (eid, pct)
as
(
    ' Do the grouping here.
    select
         e.eid, sum(w.pct_time) 
    from
       emp e
    inner join  
       works w on w.eid = e.eid
    group by
        e.eid
)
' And now you can join the grouped results with the employees to display the names
select 
   [w].pct as 'Total', e.ename 
from 
   [emp] e
inner join  
   [grouped] w on w.eid = e.eid;