I am trying to use CASE in my query. I have to calculate the difference between required_number and vehicle_quantity. If it is less than or equal to 0 then I need value 0 otherwise the difference value. I am trying following code directly in phpmyadmin. But I am getting error:
Notice in ./libraries/sql-parser/src/Utils/Query.php#427
Undefined property: SqlParser\Components\CaseExpression::$expr
This is the query I have tried so far.
SELECT
required_number,
vehicle_quantity,
CASE
WHEN (
required_number - vehicle_quantity
) <= 0 THEN
'0'
ELSE
(
required_number - vehicle_quantity
)
END AS income_amt
FROM
vehicles
WHERE
id = 22
Can anybody help me what mistake I did in my query. Thank You.
Try this:
SELECT required_number,
vehicle_quantity,
(CASE
WHEN ((required_number - vehicle_quantity) <=0) THEN 0
ELSE (required_number - vehicle_quantity)
END) AS extra
FROM vehicles
WHERE mun_id=22
TRY THIS: you have to use 0 instead of '0' because you are doing integer based calculation so you can't define string instead
SELECT
required_number,
vehicle_quantity,
CASE WHEN (required_number - vehicle_quantity) <= 0 THEN
0
ELSE
(required_number - vehicle_quantity)
END AS income_amt
FROM vehicles
WHERE id = 22
Related
I use case when in MySQL like this:
select name, age, time, countDay, dvt, total, dateLogin,
(total - datediff(NOW(), dateLogin)) as totalVal18,
(total - age) as totalVal22
case dvt
when dvt = 0 then countDay = totalVal18
when dvt = 1 then countDay = totalVal22
Update 1:
Struct table is: dvt, total, countDay is double type.
dateLogin is datetime type.
User input is dateLogin and age.
Output using countDay to check values. Like:
where countDay >= 18.
dvt is tinyint. dvt like your age > 18 or age < 18
Error like:
error like case dvt
when dvt = 0 then at line 2
When using formula it happens error? How to using the formula in case when MySQL?
You have incorrectly combined the 2 versions of the case structure.
Either use
case dvt
when 0 then totalVal18
when 1 then totalVal22
end as countDay
Or
case
when dvt = 0 then totalVal18
when dvt = 1 then totalVal22
end as countDay
forms. See mysql's documentation on case
Update
You cannot use column aliases this way, you need to include the formula in the case statement as well.
Check this Sample Here table refers to your table name
SELECT CASE
WHEN dvt > 18 THEN 1
ELSE 0 END AS
countDay
FROM table
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.
I'm about to build some sort of function or query where I can check if a certain record already exists in the database. The following rules apply:
The table has 6 columns
My yet-to-build-query has access to a complete row-object (all 6 values)
This query should find each row with at least 4 out of 6 corresponding values from the object I passed
Using MySQL
Is it even possible to build a query like this? My goal is to have a function which can return true if it's likely that a row like the passed object is already existing in the database.
Is my only option to make a query with multiple where-statements (where I try for each combination 4 different values)?
pseudo:
function getSimilarRow(Row_Object $row)
{
//select *
//from table_x
//where 4 out of 6 properties from object $row apply
}
You could use a case statement in the where clause for each property you are trying to match. If it meets the criteria then give the case statement a value of 1; if it doesn't then give it 0. The sum of the cases should then be >= 4.
I'm not that familiar with MySQL but the following will work (I knocked up a quick SQL Fiddle to show it working):
select * from SomeTable where
(case when propertyOne = 'value1' then 1 else 0 end) +
(case when propertyTwo = 'value2' then 1 else 0 end) +
(case when propertyThree = 'value3' then 1 else 0 end) +
(case when propertyFour = 'value4' then 1 else 0 end) +
(case when propertyFive = 'value5' then 1 else 0 end) +
(case when propertySix = 'value6' then 1 else 0 end) >= 4
Obviously you could change your logic in each clause if you'd prefer them to be likes or anything. You could even apply a weighting to each column by using something other than just 1 if you needed to get really creative.
I my order by clause I want to do something like
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
how can I write
order by case when MyDate is null then 1 else 0 end, MyDate
in Zend
I already tried
->order('by case when MyDate is null then 1 else 0 end', 'MyDate')
suggestions?
Following what I found on this article, MySQL Orderby a number, Nulls last, this maybe could work for you:
->order(new Zend_Db_Expr("-MyDate DESC"));
Would be nice to provide us with error message or echo $select so we could see where problem is.
Try this:
->order(new Zend_Db_Expr('case when MyDate is null then 1 else 0 end, MyDate'));
Passing Zend_Db_Expr object always puts it in query 'as it is' with no modification.
I have two months with two values, for example:
July-2013 1838.08
Aug-2013 3500.08
How can I calculate the percentage difference in August compared with July?
The formula for this is easy it's (Curr-Prev)*100.0/Prev, what's not clear is how to apply it since we do not know your table definition, contents or keys, and thus do not know how to generically select one month and it's previous value. But, hard-coding it would be like this:
SELECT
100.0*(curr.Val - prev.Val) / prev.Val As PercentDiff
FROM yourTable As curr
JOIN yourTable As prev
ON curr.MonthStr = 'Aug-2013' AND prev.MonthStr = 'July-2013'
The problem with working out percentage changes is that you need to be careful of when the 'old value' is 0 or you will get an error.
One approach is using nullif(old_Value, 0) but then the problem with that is when old values are 0 you are asking for New_Value/NULL which is the new value. (definitely not the % change)
I worked around it like this:
(case
when
OldValue = 0 and NewValue = 0
then
cast(0 as Decimal(10,2))
when
OldValue = 0
then
'Na'
else
cast(cast(
(
(
(cast(NewValue as decimal(11,3)) -
cast(OldValue as decimal(11,3))
)*100
)/cast(OldValue as decimal(11,3))
) as decimal(20,3)
) as varchar
)
end) '% Change'
I probably threw a lot more casts than necessary but it works well for me. Gives Na when necessary and 0 when necessary.
SELECT VAR(Bonus) 'Variance',
STDEVP(Bonus) 'Standard Deviation',
STDEV(Bonus) 'Standard Deviation',
VARP(Bonus) 'Variance for the Population'
FROM Sales.SalesPerson;
giving credit to fololwing post
http://blog.sqlauthority.com/2008/01/20/sql-server-introduction-to-statistical-functions-var-stdevp-stdev-varp/
to handle zeroes in the denominator, i use:
case
when oldVal<>0 then ((newVal-oldVal)*100.0)/oldVal
else
case when newVal=0 then 0 else Null end
end
this will return 0 if newVal and oldVal are both 0, and Null if oldVal is zero but newVal is non-zero.
multiplying by 100.0 (as opposed to 100) will implicitly convert int fields into decimal. i find it cleaner than try_convert().