SQL query to get value based on some values in fields - mysql

I have a MySQL database with a table named generations the structure of the table is as follows
I want to get value 10 as output when ten_generation have value 1 otherwise it will not return any value, 20 as output if twenty_generation have value 1 otherwise it will not return any value, 30 as output if thirty_generation have value 1 otherwise it will not return any value. If all the three fields has a value 1 output will be 10,20,30 also the task_id will provided as the input.

Its unclear what you intend the output to be when multiple generation columns are 1 but one solution is to use a CASE statement:
SELECT CASE
WHEN ten_generation = 1 THEN 10
WHEN twenty_generation = 1 THEN 20
WHEN thirty_generation = 1 THEN 30
ELSE NULL
END AS value
FROM generations
WHERE id = :your_id
If you want it as multiple columns then:
SELECT CASE
WHEN ten_generation = 1
THEN 10
ELSE NULL
END AS ten_value,
CASE
WHEN twenty_generation = 1
THEN 20
ELSE NULL
END AS twenty_value,
CASE
WHEN thirty_generation = 1
THEN 30
ELSE NULL
END AS thirty_value
FROM generations
WHERE id = :your_id
if only twenty_generation contain value 1 the output is 20 and if twenty_generation and ten_generation contain value 1 output is 10,20
Oracle Query:
SELECT TRIM(
LEADING ',' FROM
CASE WHEN ten_generation = 1 THEN '10' END
|| CASE WHEN twenty_generation = 1 THEN ',20' END
|| CASE WHEN thirty_generation = 1 THEN ',30' END
) AS value
FROM generations
WHERE id = :your_id

For MySQL you'd use CONCAT_WS:
select
concat_ws(',',
case when ten_generation = 1 then '10' end,
case when twenty_generation = 1 then '20' end,
case when thirty_generation = 1 then '30' end
) as result
from mytable
where task_id = 2;

Related

How to update a record conditionally with a field value in the same record in MySQL? [duplicate]

I would like to do the following.
Update a field based on the value of another field like
update table set if(fielda=1){fieldb=2 fieldc=3}else{fieldd=2 fielde=3}
I know this is not valid mysql but its the best way for me to describe the problem.
update table set
b = case when a = 1 then 2 else b end,
c = case when a = 1 then 3 else c end,
d = case when a = 1 then d else 2 end,
e = case when a = 1 then e else 3 end
edit
according to your comment try this:
update table set
datefield_a = case when field_a = 1 then now() else datefield_a end,
datefield_b = case when field_a <> 1 then now() else datefield_b end
I think this syntax will achieve the result you attempted to specify.
UPDATE mytable
SET fieldb = CASE WHEN fielda = 1 THEN 2 ELSE fieldb END
, fieldc = CASE WHEN fielda = 1 THEN 3 ELSE fieldc END
, fieldd = CASE WHEN fielda = 1 THEN fieldd ELSE 2 END
, fielde = CASE WHEN fielda = 1 THEN fielde ELSE 3 END
The "trick" here is that we are updating all four columns, but in some "cases", we are assigning the current value of the column back to the column, resulting in no real change to the column value. (Once you get your mind bent around that idea, it's pretty easy.)
With MySQL, we do have a handy IF function (not available in most other RDBMS) that we can use to abbreviate that a bit, and achieve the same thing:
UPDATE mytable
SET fieldb = IF(fielda = 1, 2, fieldb)
, fieldc = IF(fielda = 1, 3, fieldc)
, fieldd = IF(fielda = 1, fieldd, 2)
, fielde = IF(fielda = 1, fielde, 3)
The pain is that you still have to repeat that same conditional test multiple times.
A single scan through the table (like these statements do), and getting all those assignments done in one fell swoop is going to be faster (and more efficient) than breaking this up and doing the assignments piecemeal using multiple statements.

Select * from table WHERE `column` = x if `column` != -1

I need to make a select like,
Select * from table WHERE column = x if column != -1
but i have no idea for now.
Anyone know or made in past something like that?
Thanks.
You should also write like this,
Select * from table
WHERE
1 = case when column != -1 then
case when column = x then 1 else 0 end
else 1 end
You can utilize case when in where clause.
Similarly you can add more conditional criteria like,
Select * from table
WHERE
1 = case when column != -1 then
case when column = x then 1 else 0 end
else 1 end
AND
1 = case when column1 [conditional operator] value then
case when column1 = xx then 1 else 0 end
else 1 end
This is just an example how you can integrate more conditional criteria together, even though you can add more case when in else part even.

Error 1366 - Incorrect decimal value: '' for column '' at row -1

I've got a rather large query that is trying to get a list of carriers and compare the amount of insurance they have on record to identify carriers that do not meet a minimum threshold. If I run the select query it works just fine with no errors. But when I try to use it for an insert into a table it returns this error message
[Err] 1366 - Incorrect decimal value: '' for column '' at row -1
I have to use the cast as decimal at the bottom of this query because the value that is being stored in the database is a varchar and I cannot change that.
Anyone have any ideas?
set #cw_days = 15;
INSERT INTO carrier_dnl (carrier_id, dnl_reason_id, status_id)
SELECT work_cw_carrier_status_update.carrier_id, company_dnl_schema.dnl_reason_id,
CASE
WHEN work_cw_carrier_status_update.comparison_date > #cw_days THEN 1
ELSE 4
END as status
FROM work_cw_carrier_status_update
JOIN company_dnl_schema
ON company_dnl_schema.dnl_reason_id = 51
LEFT OUTER JOIN carrier_insurance
ON carrier_insurance.carrier_id = work_cw_carrier_status_update.carrier_id
WHERE ifnull(carrier_insurance.insurance_type_id,4) = 4
AND date(now()) BETWEEN IFNULL(carrier_insurance.insurance_effective_date,DATE_SUB(now(),INTERVAL 1 day)) AND IFNULL(carrier_insurance.insurance_expiration_date,DATE_ADD(now(),INTERVAL 1 day))
AND CASE WHEN NULLIF(carrier_insurance.insurance_bipdto_amount,'') is null THEN 0 < company_dnl_schema.value
ELSE
ifnull(cast(replace(carrier_insurance.insurance_bipdto_amount, '*','') as decimal),0) < company_dnl_schema.value
END
AND ( work_cw_carrier_status_update.b_bulk = 0 OR work_cw_carrier_status_update.b_bulk = 1 )
AND ( work_cw_carrier_status_update.b_otr = 1 OR work_cw_carrier_status_update.b_ltl = 1
OR work_cw_carrier_status_update.b_dray = 1 OR work_cw_carrier_status_update.b_rail = 1
OR work_cw_carrier_status_update.b_intermodal = 1 OR work_cw_carrier_status_update.b_forwarder = 1
OR work_cw_carrier_status_update.b_broker = 1 )
group by work_cw_carrier_status_update.carrier_id;`
If the select seems to work, then there are two possible problems. The first is that the select doesn't really work and the problem appears further down in the data. Returning one or a handful of rows is not always the same as "working".
The second is an incompatibility with the types for the insert. You can try to use silent conversion to convert the values in the select to numbers:
SELECT work_cw_carrier_status_update.carrier_id + 0, company_dnl_schema.dnl_reason_id + 0,
(CASE WHEN work_cw_carrier_status_update.comparison_date > #cw_days THEN 1
ELSE 4
END) as status
This may look ugly, but it is not nearly as ugly as storing ids as strings in one table and as numbers in another.

How can I use "OR" condition in MySQL CASE expression?

I have a procedure that contains CASE expression statement like so:
BEGIN
....
WHILE counter < total DO
....
CASE ranking
WHEN 1 OR 51 OR 100 OR 167 THEN SET
project_name = 'alpha';
WHEN 2 THEN SET
project_name = 'beta';
WHEN 10 OR 31 OR 40 OR 61 THEN SET
project_name = 'charlie';
....
ELSE SET
project_name = 'zelta';
END CASE;
INSERT INTO project (id, name) VALUES (LAST_INSERT_ID(), project_name);
SET counter = counter + 1;
END WHILE;
END
$$
DELIMITER ;
When I call the above procedure, cases with OR statements are either skipped completely or only the first item in the list is matched. What am I doing wrong?
CASE ranking
WHEN 1 THEN 'alpha'
WHEN 2 THEN 'beta'
WHEN 10 THEN 'charlie'
ELSE 'zelta'
END CASE;
You can use one of expresions that WHEN has, but you cannot mix both of them.
1) WHEN when_expression
Is a simple expression to which input_expression is compared when the simple CASE format is used. when_expression is any valid expression. The data types of input_expression and each when_expression must be the same or must be an implicit conversion.
2) WHEN Boolean_expression
Is the Boolean expression evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression.
You could program:
1)
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
2)
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
But in any case you can expect that the variable ranking is going to be compared in a boolean expresion.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
you can use in to compare the values both numeric or character
CASE
WHEN ranking in(1,2,3) THEN '1Q'
WHEN ranking in(4,5,6) THEN '2Q'
ELSE '3Q'
END CASE;
CASE
WHEN ranking in('1','2','3') THEN '1Q'
WHEN ranking in('4','5','6') THEN '2Q'
ELSE '3Q'
END CASE;
this will also work in select statement and stored procedure also.
select case when month(curdate()) in (4,5,6) then 1 when month(curdate()) in (7,8,9) then 2 else 3 end as fiscal_quarter ;
This is also possible:
select (case when (var1 = 0 or var2 = 1) then 'x' else 'y' end)
from...

Update Query based on condition

I would like to do the following.
Update a field based on the value of another field like
update table set if(fielda=1){fieldb=2 fieldc=3}else{fieldd=2 fielde=3}
I know this is not valid mysql but its the best way for me to describe the problem.
update table set
b = case when a = 1 then 2 else b end,
c = case when a = 1 then 3 else c end,
d = case when a = 1 then d else 2 end,
e = case when a = 1 then e else 3 end
edit
according to your comment try this:
update table set
datefield_a = case when field_a = 1 then now() else datefield_a end,
datefield_b = case when field_a <> 1 then now() else datefield_b end
I think this syntax will achieve the result you attempted to specify.
UPDATE mytable
SET fieldb = CASE WHEN fielda = 1 THEN 2 ELSE fieldb END
, fieldc = CASE WHEN fielda = 1 THEN 3 ELSE fieldc END
, fieldd = CASE WHEN fielda = 1 THEN fieldd ELSE 2 END
, fielde = CASE WHEN fielda = 1 THEN fielde ELSE 3 END
The "trick" here is that we are updating all four columns, but in some "cases", we are assigning the current value of the column back to the column, resulting in no real change to the column value. (Once you get your mind bent around that idea, it's pretty easy.)
With MySQL, we do have a handy IF function (not available in most other RDBMS) that we can use to abbreviate that a bit, and achieve the same thing:
UPDATE mytable
SET fieldb = IF(fielda = 1, 2, fieldb)
, fieldc = IF(fielda = 1, 3, fieldc)
, fieldd = IF(fielda = 1, fieldd, 2)
, fielde = IF(fielda = 1, fielde, 3)
The pain is that you still have to repeat that same conditional test multiple times.
A single scan through the table (like these statements do), and getting all those assignments done in one fell swoop is going to be faster (and more efficient) than breaking this up and doing the assignments piecemeal using multiple statements.