抱歉格式化问题!我不知道它在这个网站上有效:(
我试图在1月份的销售表中仅返回最高的总计,但它会返回该月的每笔销售而不仅仅是最高的。
select
EMP.FirstName,
EMP.LastName,
EMP.Email,
SAL.SaleNumber,
SAL.SaleDate,
max(SAL.Total) Total
from
Employee EMP
INNER JOIN Sale SAL
ON EMP.EmployeeNumber = SAL.EmployeeNumber
--Assuming the month is January of 2015, because there were no sales for this month (March).
where
SAL.SaleDate between '20150101 00:00:00.000' and '20150131 23:59:59.997'
group by
EMP.FirstName,
EMP.LastName,
EMP.Email,
SAL.SaleNumber,
SAL.SaleDate,
SAL.Total
答案 0 :(得分:1)
我认为您希望在给定的时间范围内获得每位员工的最高销售额?如果是这样,一种选择是使用排名函数,例如row_number
:
with cte as (
select
EMP.FirstName,
EMP.LastName,
EMP.Email,
SAL.SaleNumber,
SAL.SaleDate,
SAL.Total,
row_number() over (partition by EMP.EmployeeNumber
order by SAL.Total DESC) rn
from
Employee EMP
INNER JOIN Sale SAL
ON EMP.EmployeeNumber = SAL.EmployeeNumber
where
SAL.SaleDate >= '20150101 00:00:00.000' and
SAL.SaleDate < '20150201 00:00:00.000'
)
select *
from cte
where rn = 1
另请注意,我建议您使用>=
和<
进行此类日期过滤。
答案 1 :(得分:0)
我假设正在寻找最畅销的产品。您的查询获得每个销售数量的最高销售额,最终成为每次销售。
select top 1
EMP.FirstName,
EMP.LastName,
EMP.Email,
SAL.SaleNumber,
SAL.SaleDate,
SAL.Total
from
Employee EMP
INNER JOIN Sale SAL
ON EMP.EmployeeNumber = SAL.EmployeeNumber
Order by sal.total desc