Ask Your Question
0

How to assign a value under certain conditions by referring to different criteria in a separate table using SQL?

asked 2023-05-30 00:58:07 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-30 01:11:02 +0000

david gravatar image

You can assign a value under certain conditions by joining the table with the criteria table and using a CASE statement to set the value based on the criteria.

Example:

Table A (customers):

| customerid | customername | category | |-------------|---------------|----------| | 1 | John Smith | | | 2 | Mary Johnson | | | 3 | James Brown | |

Table B (criteria):

| category | minimum_sales | |----------|---------------| | A | 10000 | | B | 5000 | | C | 0 |

To assign a category based on minimum sales, you can join the two tables and use a CASE statement to set the category based on the minimum_sales criteria:

SELECT
  customer_id,
  customer_name,
  CASE
    WHEN sales > minimum_sales
    THEN category
    ELSE ''
  END AS category
FROM
  customers
  JOIN criteria ON customers.category = criteria.category

This query will output the following result:

| customerid | customername | category | |-------------|---------------|----------| | 1 | John Smith | C | | 2 | Mary Johnson | A | | 3 | James Brown | B |

In this example, customer John Smith does not meet the minimum sales criteria for category A or B, so the category is set to C. Mary Johnson meets the minimum sales criteria for category A, so that category is assigned. James Brown meets the minimum sales criteria for category B, so that category is assigned.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-30 00:58:07 +0000

Seen: 8 times

Last updated: May 30 '23