我正在尝试列出全名和全职处理的交易总数 员工,然后按交易总数的降序对结果进行排名。
这就是我所拥有的
select
concat( e.efirst, e.elast ) ename,
count(*) total_transactions
from
transactions t
join employees e on t.employeeid = e.employeeid
where
e.etype = 'Fulltime'
group by
t.employeeid
order by
total_transactions desc;
答案 0 :(得分:4)
在通过外键对聚合进行计算时,您需要在外部查询中JOIN
的主体关系(在这种情况下为employee
),因为它是与聚合分开的关注点。
SELECT
CONCAT( CONCAT( employee.efirst, ' ' ), employee.elast ) AS employee_name,
employee_id,
total_transactions
FROM
(
SELECT
employeeid AS employee_id,
COUNT(*) AS total_transactions
FROM
transactions
GROUP BY
employeeid
) AS sq
INNER JOIN employee ON sq.employee_id = employee.employeeid
WHERE
employee.etype = 'Fulltime'
ORDER BY
total_transactions desc;
答案 1 :(得分:1)
添加concat(e.efirst, e.elast)
进行分组:
select
concat(e.efirst, e.elast) ename,
count(*) total_transactions
from
transactions t
join employees e on t.employeeid = e.employeeid
where
e.etype = 'Fulltime'
group by
t.employeeid, concat(e.efirst, e.elast)
order by
total_transactions desc;
答案 2 :(得分:0)
group by
表达式应与select
中未聚合的表达式匹配,因此:
select ( e.efirst || ' ' || e.elast ) as ename,
count(*) total_transactions
from transactions t join
employees e
on t.employeeid = e.employeeid
where e.etype = 'Fulltime'
group by ( e.efirst || ' ' || e.elast )
order by total_transactions desc;
我还在名称之间添加了一个空格,并切换为使用串联运算符。
这假设员工姓名是唯一的。如果不是这种情况,那么您应该在select
中加入员工ID,这样您就可以在同名员工中进行区分。