Zend Framework order by ascending null values last - mysql

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.

Related

mysql date range query, when the field is not sent anything for the 'between' statement

I have this query, which returns me 7 records
Now if I add this line 'AND date_format (ds.date_emission,'% Y-% m-% d ') BETWEEN' 'AND' '', nothing returns me, I want that when the date range is empty I need that I also returned the 7 records
Please refer answer below.
I have added two variable replace inStartDate variable with a range start date and inEndDate with range end date.
SELECT ds.id
FROM documentos_salida ds
WHERE ds.terceros_id = 329
AND ds.estado =0
AND ds.tipo_documento ='Factura'
AND ds.saldo_pendiente_factura >0
AND (ds.fecha_vencimiento > now() or
ds.fetcha_vencimiento = NOW())
AND ds.numero_documento LIKE '%%'
AND ( CASE WHEN (inStartDate = '' AND inEndDate = '')
THEN TRUE
ELSE (date_format(ds.fetcha_emision, '%Y-%m-%d') BETWEEN inStartDate AND inStartDate)
END)
ORDER BY ds.fecha_emision DESC;

Symfony3-Doctrine : Order by Case When

I'm working on a Symfony 3.4 project.
I want to order a table by updated_at if exists (not null), by created_at if not.
In SQL, this works :
SELECT * FROM `contract`
ORDER BY
(CASE WHEN ISNULL(`updated_at`) THEN `created_at` ELSE `updated_at` END)
DESC
I tried a lot of things but I don't manage to make it work with Doctrine Query Builder.
First, I tried this (syntax error) :
$contracts = $em->createQuery(
'SELECT c
FROM AppBundle:Contract c
ORDER BY (CASE WHEN c.updatedAt = :update THEN c.createdAt ELSE c.updatedAt END) DESC')
->setParameter('update', NULL)
->getResult();
Then, I tried this according to this topic, but I have no result (no error) :
$contracts = $rp->createQueryBuilder('c')
->select('(CASE WHEN c.updatedAt != :update THEN 1 ELSE 0 END) AS HIDDEN orderDate')
->orderBy('orderDate', 'DESC')
->addOrderBy('c.createdAt', 'DESC')
->setParameter('update', NULL)
->getQuery()->getResult();
How can I sort my contracts by their updated date if they have been updated, or by their created date if they haven't been modified ?
If it helps, I use the DoctrineExtensions bundle for other queries, I saw IfNull and IfElse classes but I don't how to use them with my case.
After several attempts, I finally found the solution.
Use COALESCE : returns the first value not null in the list, so if A is null and B not null, then COALESCE(A,B) will return B.
$contracts = $rp->createQueryBuilder('c')
->select('c')
->addSelect('COALESCE(c.updatedAt,c.createdAt) AS HIDDEN orderDate')
->orderBy('orderDate', 'DESC')
->getQuery()->getResult();
No need to use the DoctrineExtensions bundle.

Case in the query gives undefined property error

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

CASE Statement MYSQL with Condition

I got 2 CASE statements: First CASE statement is as follows:
Case When ((cust_shipmentdate_awb Is Null OR cust_shipmentdate_awb = '')
AND (comp_shipdate_awb IS NULL OR comp_shipdate_awb = '')) Then 'Pending'
ELSE 'Shipped' End AS shipment_status
The Second CASE statement is as follows:
Case When apbg_bal_pay_amt ='0' Then 'Received'
Else 'Pending' End AS payment_status
Iam looking to write one more CASE statement named OVERALL_Status. That is basically a combination of both this CASES (shipment_status and payment_status), which means if Shipment status is 'Shipped' AND Payment_Status is 'Received' then Overall_status is 'Completed' else 'Not Completed'. Can anyone please help me on this. I am really struck here. I tried the combination of both the CASES, but not working:
Case When (cust_shipmentdate_awb Is Null OR cust_shipmentdate_awb = '') AND
(comp_shipdate_awb IS NULL OR comp_shipdate_awb = '') AND (apbg_bal_pay_amt != '0') Then
'Pending' ELSE 'Completed' End AS overall_status
There is two solutions as I see it:
1. You make the current query a subquery and add another CASE statement on the result of the subquery. (the pretty solution as I see it)
2. You add another WHEN to the existing case. Combining the clauses in the first two WHEN clauses to get the result. (probably the most optimized solution)
How about this?
(case when (cust_shipmentdate_awb Is Null OR cust_shipmentdate_awb = '') and
(comp_shipdate_awb IS NULL OR comp_shipdate_awb = '')
then 'Not Completed'
when apbg_bal_pay_amt = '0' Then 'Completed'
else 'Not Completed'
end) as overall_status

Why query give not right results?

Good day.
Table have data:
id UserIdn CommentIdn LikeIdn NewsIdn Type IsFavorite DateCreate
1 527464 613895 748153 up yes 0000-00-00 00:00:00
For get count values i use code:
SELECT
count(Type='up') as CountUp,
count(Type='down') as CountDown
FROM Likes WHERE NewsIdn = '748153'
but in result instead
CountUp CountDown
1 0
i get
CountUp CountDown
1 1
Tell me please why i get not correct results? How query will be right?
Try using a case when in a sum().
SELECT SUM(CASE WHEN Type = 'up' THEN 1 ELSE 0 END) as 'count_up'
...
The Type='up' for example in your COUNT() function is either false (0) or true (1). But COUNT() doesn't care about that, it just sees that there is a row. Use SUM() instead:
SELECT
COALESCE(SUM(Type='up'), 0) as CountUp,
COALESCE(SUM(Type='down'), 0) as CountDown
FROM Likes WHERE NewsIdn = '748153'
Try this...
SELECT
SUM(CASE WHEN Type='up' AND Type IS NOT NULL THEN 1 ELSE 0 END) as CountUp,
SUM(CASE WHEN Type='down' AND Type IS NOT NULL THEN 1 ELSE 0 END) as CountDown
FROM Likes
WHERE NewsIdn = '748153'