有表Employees
CREATE TABLE Employees
(
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name nvarchar(100) NOT NULL,
depID int NOT NULL,
salary money NOT NULL,
FOREIGN KEY (depID) REFERENCES Departments(id)
);
和Payments
CREATE TABLE Payments
(
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
userID int NOT NULL,
createdDate date DEFAULT GETDATE(),
sum money NOT NULL,
FOREIGN KEY (userID) REFERENCES Employees(id)
);
过去两年我需要获得前三名薪水的员工姓名 我尝试使用下面的查询,但它没有工作,我收到了一个错误。
SELECT TOP 3 name
FROM Employees
WHERE id in (SELECT id, SUM(sum) as SumTotal FROM Payments
WHERE (createdDate BETWEEN '2015-09-01' AND '2013-09-01')
ORDER BY SumTotal);
错误讯息:
ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP或FOR XML。
如何让它发挥作用?
答案 0 :(得分:2)
这是使用cte
s。
with pymt as
(
SELECT userid, sum(sum) as sumtotal
FROM Payments
WHERE createdDate BETWEEN '2013-09-01' AND '2015-09-01'
group by userid
)
, ename as
(
select e.name, pymt.sumtotal, row_number() over(order by pymt.sumtotal desc) as rn
from pymt join employees e
on pymt.userid = e.id
)
select name
from ename
where rn < = 3;
答案 1 :(得分:1)
试试这个: -
SELECT userID, SUM(sum) as SumTotal INTO #temp
FROM Payments
WHERE (createdDate BETWEEN '2015-09-01' AND '2013-09-01')
group by userID
ORDER BY SumTotal
SELECT TOP 3 name
FROM Employees e join #temp
on e.id = #temp.userID
答案 2 :(得分:1)
您必须执行错误消息告诉您的操作,将TOP放在您的订单所在地:
SELECT name
FROM Employees
WHERE id in (SELECT TOP 3 id, SUM(sum) as SumTotal FROM Payments
WHERE (createdDate BETWEEN '2015-09-01' AND '2013-09-01')
ORDER BY SumTotal)
[编辑] 如果我们按照错误消息,这应该没问题:
SELECT name
FROM Employees
WHERE id in ( Select x.userId From (SELECT TOP 3 userId, SUM([sum]) as SumTotal FROM Payments
WHERE (createdDate BETWEEN '2015-09-01' AND '2013-09-01')
Group By userId
ORDER BY SumTotal) x);
答案 3 :(得分:1)
select top 3
emp.id as id,
emp.name as name,
sum(pay.sum) as total
from employees emp
join payments pay
on emp.id = pay.user_id
--where pay.createdDate BETWEEN '2015-09-01' AND '2013-09-01'
where pay.createdDate BETWEEN '2013-09-01' AND '2015-09-01'
group by emp.id, emp.name
这应该有效
答案 4 :(得分:1)
人们过于复杂化了。我很确定这会得到你想要的东西:
SELECT TOP 3 employees.id, Name,
Sum([sum]) AS [TotalPayments]
FROM Employees
inner join Payments on employees.id = payments.userid
WHERE createdDate BETWEEN '2013-09-01' and '2015-09-01'
Group By employees.id, Name
Order BY TotalPayments DESC
SqlFiddle来测试它
如果只需要names列,可以使用另一个select包装该查询:
select Name from (
SELECT TOP 3 employees.id, Name,
Sum([sum]) AS [TotalPayments]
FROM Employees
inner join Payments on employees.id = payments.userid
WHERE createdDate BETWEEN '2013-09-01' and '2015-09-01'
Group By employees.id, Name
Order BY TotalPayments DESC
) q
答案 5 :(得分:-1)
SELECT TOP 3 Name,
Sum(sum) AS sum
FROM Employees
WHERE createdDate BETWEEN '2015-09-01' AND '2013-09-01'
Group By Name
Order BY 2 DESC