简体   繁体   中英

Add values in new column based on multiple conditions

I am new to sql and using sql server 2019. I have 3 columns- Code, Rep, Area in a table. Based on certain conditions in these columns, I need to create 2 new columns- Business and Plant with values. I have tried to use if-then-else and case-when statements. But they are giving error when I add multiple conditions. Please help with the query to create these new columns in the basis of conditions below. Hope this table below helps-

select *,Business case when code in ('A231', B343') and Rep='Alex' then Business='Steel' else Null End as Business
Error - Incorrect Syntax near keyword 'case'

Input table -

Code Rep Area
A231 Alex Del
B343 Alen Mum
Condition Bus Plant
Code=['A231','B343'] and Rep=['Alex'] and Area=['Del'] Steel EXR
Code=['A231','B343'] and Rep=['Alen'] and Area=['Mum'] Iron EXR

Output table -

Code Rep Area Business Plant
A231 Alex Del Steel EXR
B343 Alen Mum Iron EXR

If you were to store these conditions in a proper format, such as JSON, you could use OPENJSON to crack open the arrays and semi-join that to get the correct rows.

For example:

INSERT INTO Conditions
  (Bus, Plant, Condition)
VALUES
  ('Steel', 'EXR', '{"Code":["A231","B343"], "Rep":["Alex"], "Area":["Del"]}'),
  ('Iron', 'EXR', '{"Code":["A231","B343"], "Rep":["Alen"], "Area":["Mum"]}');
SELECT
  i.*,
  c.Bus,
  c.Plant
FROM Input i
JOIN Conditions c
    CROSS APPLY OPENJSON(c.Condition)
      WITH (
        Code nvarchar(max) AS JSON,
        Rep  nvarchar(max) AS JSON,
        Area nvarchar(max) AS JSON
      ) j
   ON i.Code IN (SELECT j2.value FROM OPENJSON(j.Code) j2)
  AND i.Rep  IN (SELECT j2.value FROM OPENJSON(j.Rep ) j2)
  AND i.Area IN (SELECT j2.value FROM OPENJSON(j.Area) j2);

db<>fiddle

The first OPENJSON returns a schema of the three arrays.

Then you use OPENJSON again without a schema to return each array element.

You can modify your current data with this code, to return proper JSON

UPDATE Conditions
SET Condition = '{"' +
  REPLACE(
    REPLACE(
      REPLACE(
        Condition,
        ' and ',
        ',"'
      ),
      '=[',
      '":['
    ),
    '''',
    '"'
  ) + '}';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM