如何在SQL Server中使用CASE WHEN函数

时间:2019-05-10 00:23:50

标签: sql sql-server case case-when

我正在尝试解决此问题,但不确定使用CASE WHEN是否是正确的解决方案。

我正在尝试处理数据。如果乘积等于A,则价格必须为100,而不是表中的价格,我不确定如何实现。

CREATE TABLE Test 
(
     Product VARCHAR(250), 
     subproduct VARCHAR(250), 
     Orderdate DATETIME
);

INSERT INTO TEST (product, subproduct, orderdate)  
VALUES ('A', 'blue',  '2019/01/01'), 
       ('B', 'orange','2019/01/11'),  
       ('C', 'lemon', '2019/01/15'),  
       ('D', 'lemon', '2019/01/20'),
       ('A', 'blue',  '2019/12/31'), 
       ('B', 'orange','2019/12/31'),  
       ('C', 'lemon', '2019/12/15'),  
       ('D', 'lemon', '2019/12/31');

CREATE TABLE PriceTest 
(
     Product VARCHAR(250), 
     Price NUMERIC(10,2), 
     Pricedate DATETIME
)

INSERT INTO PriceTest (product, price, pricedate)  
VALUES ('A', 10.00,'2019/12/31'), 
       ('B', 50.00,'2019/12/31'),  
       ('C', 30.00,'2019/12/31'),  
       ('D', 50.00,'2019/12/31'),
       ('A', 20.00,'2019/10/31'), 
       ('B', 40.00,'2019/10/31'),  
       ('C', 50.00,'2019/10/31'),  
       ('D', 10.00,'2019/11/30');

选择查询:

SELECT
    t.product, t.subproduct, p.price, p.pricedate 
FROM
    test t
JOIN
    pricetest p ON p.product = t.product 
WHERE 
    p.pricedate = '12/31/2019' 
ORDER BY
    t.product

当前结果:

   product  subproduct  price   pricedate
   ---------------------------------------
    A       blue        10      12/31/2019
    A       blue        10      12/31/2019
    B       orange      50      12/31/2019
    B       orange      50      12/31/2019
    C       lemon       30      12/31/2019
    C       lemon       30      12/31/2019
    D       lemon       50      12/31/2019
    D       lemon       50      12/31/2019

所需结果:每当产品= A时,价格应= 100,否则其他产品的价格与价格测试表相同。

   product  subproduct  price   pricedate
   ---------------------------------------
     A      blue        100     12/31/2019
     A      blue        100     12/31/2019
     B      orange      50      12/31/2019
     B      orange      50      12/31/2019
     C      lemon       30      12/31/2019
     C      lemon       30      12/31/2019
     D      lemon       50      12/31/2019
     D      lemon       50      12/31/2019

1 个答案:

答案 0 :(得分:1)

是的,您可以使用CASE来做到这一点:

select 
    t.product
    ,t.subproduct
    ,CASE WHEN t.product = 'A' 
        THEN 100
        ELSE p.price
    END AS price
    ,p.pricedate 
from 
    test t
    join pricetest p on p.product = t.product 
where 
    p.pricedate = '20191231' 
order by t.product

顺便说一句,您实际上应该对SQL Server中的日期文字使用以下格式:YYYYMMDD

不要写

pricedate = '12/31/2019' 

pricedate = '20191231' 

有关更多详细信息,请参见Bad habits to kick : mis-handling date / range queries