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

时间:2018-07-24 06:05:31

标签: mysql sql sql-server

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

样本表输出应如下

EmpID        salesman    year  SaleIncreased
7843921      John        2016   Null
7843921      John        2017   Yes 
7843934      Neil        2016   Null
7843934      Neil        2017   No

我已经使用CASE WHEN语句进行自我联接,如下所示:

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'

我无法获得所需的输出。

2 个答案:

答案 0 :(得分:1)

您的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)。

答案 1 :(得分:0)

这有用吗??

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