Mysql 在SQL中实现CASE-WHEN语句时出错

Mysql 在SQL中实现CASE-WHEN语句时出错,mysql,sql,sql-server,Mysql,Sql,Sql Server,我必须写一个查询,检查每个销售人员的销售额与上一年的业绩相比是否增加(使用是)和减少(在saleRegress列中使用否) 示例表输出应如下所示 EmpID salesman year SaleIncreased 7843921 John 2016 Null 7843921 John 2017 Yes 7843934 Neil 2016 Null 7843934 Neil

我必须写一个查询,检查每个销售人员的销售额与上一年的业绩相比是否增加(使用是)和减少(在
saleRegress
列中使用否)

示例表输出应如下所示

EmpID        salesman    year  SaleIncreased
7843921      John        2016   Null
7843921      John        2017   Yes 
7843934      Neil        2016   Null
7843934      Neil        2017   No
select t1.empid, t1.salesman, t1.year
from Sales_temp as t1
inner join Sales_temp as t2
on t1.empid = t2.empid and t2.year = t1.year - 1 
case when t1.sale > t2.sale 
then 'Yes' 
else 'No' 
end as 'SaleIncreased'
我使用了self-join和
CASE WHEN
语句,如下所示

EmpID        salesman    year  SaleIncreased
7843921      John        2016   Null
7843921      John        2017   Yes 
7843934      Neil        2016   Null
7843934      Neil        2017   No
select t1.empid, t1.salesman, t1.year
from Sales_temp as t1
inner join Sales_temp as t2
on t1.empid = t2.empid and t2.year = t1.year - 1 
case when t1.sale > t2.sale 
then 'Yes' 
else 'No' 
end as 'SaleIncreased'

我无法获得所需的输出

您的
CASE
表达式似乎不合适,您可能希望它出现在
SELECT
子句中:

SELECT
    t1.empid,
    t1.salesman,
    t1.year,
    CASE WHEN t1.sale > t2.sale 
         THEN 'Yes' 
         ELSE 'No' 
    END AS SaleIncreased
FROM Sales_temp AS t1
LEFT JOIN Sales_temp AS t2
    ON t1.empid = t2.empid AND t2.year = t1.year - 1
ORDER BY
    t1.empid,
    t1.year;
我做的另一个改变是使用左连接而不是内部连接。这一点很重要,因为这将确保每个员工的最早年份记录出现在结果集中(这些记录的销售额增加值为
NULL

这有用吗

DECLARE @tab1 TABLE(EMPID BIGINT,Saleman VARCHAR(100),[Year] BIGINT,Sales BIGINT)
INSERT INTO @tab1
SELECT 7843921,'John',2016,100 Union ALL
SELECT 7843921,'John',2017,150 Union ALL
SELECT 7843934,'Neil',2016,120 Union ALL
SELECT 7843934,'Neil',2017,90

Select *,CASE 
        WHEN LAG(Sales) OVER(Partition by EmpID order by [year]) IS NULL then NULL
        WHEN Sales - LAG(Sales) OVER(Partition by EmpID order by [year])>0 THEN 'Yes' 
        ELSE 'No' END 
from @tab1

请同时提供示例输入。首先,确定您使用的是哪种数据库产品。是两种截然不同的产品。问题很少被正确地标记为both@Damien_The_Unbeliever虽然随着MySQL 8的出现,这已经不是什么坏事了。。。有点^^^完美!!谢谢你,伙计。我是个新手,确实会犯愚蠢的错误。