I am trying to make this query work, here is my logic , I am trying to select record thats there is not at LEAST NOT one of these options:
1). status = Approved AND end_date >now
2). status =Approved AND end_date is NULL
3). status = Pending And end_date is NULL & COUNT(id) =1
4). status =Pending AND end_date >now & COUNT(id) =1
5). status =Pending AND end_date <now & COUNT(id) =1
how to accomplish this , this is what I have so far I am not sure how to check for COUNT(id) = 1 in conditions 3, 4, and 5?
SELECT
*
FROM
outreach
WHERE
NOT EXISTS (
SELECT
*
FROM
outreach_links
WHERE
outreach_links.outreach_id = outreach.id
AND STATUS = "Approved"
AND end_date > now()
)
AND NOT EXISTS (
SELECT
*
FROM
outreach_links
WHERE
outreach_links.outreach_id = outreach.id
AND STATUS = "Approved"
AND end_date IS NULL
)
AND NOT EXISTS (
SELECT
*
FROM
outreach_links
WHERE
outreach_links.outreach_id = outreach.id
AND STATUS = "Pending"
AND end_date > now()
)
AND NOT EXISTS (
SELECT
*
FROM
outreach_links
WHERE
outreach_links.outreach_id = outreach.id
AND STATUS = "Pending"
AND end_date IS NULL
)
AND NOT EXISTS (
SELECT
*
FROM
outreach_links
WHERE
outreach_links.outreach_id = outreach.id
AND STATUS = "Pending"
AND end_date < now()
)
select
o.*,
SUM(if(ol.status = "Approved" and (ol.end_date > now() or end_date is null), 1, 0)) as cond1,
SUM(if(ol.status = "Pending" and (ol.end_date != now() or end_date is null), 1, 0)) as cond2
from
outreach o
left join
outreach_links ol on ol.outreach_id = o.id
group by
o.id
having
cond1 = 0 and cond2 != 1
;
Not sure if that's you are looking for, but you can try it.
cond2 != 1 makes your COUNT(id) = 1 condition (if there are more than one linked id in outreach_links cond2 will be greater than 1)
Related
I have written a complex query in MySQL to return a result.
it works perfectly
Until .....
the subquery returns no result
how to write an if or IF null then substitute in date '2020-06-03'
any help greatly appreciated
SELECT
*
FROM
trades
WHERE
stock_code = 'IHVV'
AND acc_id = '4'
AND tx_date >
(SELECT tx_date
FROM
( SELECT *, ( #sum_units := #sum_units + units ) AS sum_units
FROM
trades
JOIN ( SELECT #sum_units := 0 ) params
WHERE
stock_code = 'IHVV'
AND acc_id = '4'
AND tx_date <= '2021-06-30'
AND ( transfer_date IS NULL OR transfer_date <= '2021-06-30' )
ORDER BY
tx_date ASC,
units ASC
) AS query1
WHERE
tx_date < DATE_SUB( '2021-06-30', INTERVAL 1 YEAR )
AND sum_units = 0
ORDER BY
tx_date DESC
LIMIT 1
)
AND tx_date <= '2021-06-30'
AND ( transfer_date IS NULL OR transfer_date <= '2021-06-30' )
ORDER BY
tx_date ASC,
units ASC
clarification
I have written a main query and in one of the where clauses I am using a subquery and this subquery works well, until this subquery does not return a result and my main query stops working, so I would like to on no result in this subquery substitute a value on no result so the main query can function normally
example needed
select * from table where date > (ifnull(subquery, "2002-01-01"))
I get
incorrect parameter count in the call to native function "IFNULL'
AND THE ANSWER IS: ---> :)
thanks guys for all your suggestions
much appreciated
SELECT *
FROM trades
WHERE stock_code = 'IHVV'
AND acc_id = '4'
AND tx_date >
#last 0 date out of 1 year perhaps change the date range by from date and to date in the interval 1 year area
(SELECT COALESCE(
(SELECT tx_date
FROM (SELECT *, (#sum_units := #sum_units + units) AS sum_units
FROM trades
JOIN ( SELECT #sum_units := 0 ) params
WHERE stock_code = 'ANZ'
AND acc_id = '4'
AND tx_date <= '2022-06-30'
AND (transfer_date IS NULL OR transfer_date <= '2022-06-30' ))
ORDER BY tx_date ASC, units ASC) as query1
WHERE tx_date < DATE_SUB('2022-06-30',INTERVAL 1 YEAR)
AND sum_units = 0
ORDER BY tx_date DESC
LIMIT 1), 'TODATE')
AND tx_date <= '2022-06-30'
AND (transfer_date IS NULL OR transfer_date <= '2022-06-30' )
ORDER BY tx_date ASC, units ASC
decreasing running time (select query executing time)
even query is not working
it is reducing code line
there are 80 tables
select
(ant_return_loss_pass='pass')+(ant_cross_isolation_pass='pass') as pass_count,
(ant_return_loss_pass='fail')+(ant_cross_isolation_pass='fail') as fail_count,
(ant_return_loss_pass='') +(ant_cross_isolation_pass='') as blank_count
from
(
select A.serial_no,
A.pass_fail as ant_return_loss_pass
from ant_return_loss A,
(
select max(register_date) as date
from ant_return_loss
where 1=1
and serial_no >= '184500074'
and serial_no <= '184500076'
group by serial_no
) B
where 1 = 1
and A.register_date = B.date
)AA
,(
select A.serial_no,
A.pass_fail as ant_cross_isolation_pass
from ant_cross_isolation A,
(
select max(register_date) as date
from ant_cross_isolation
where 1=1
and serial_no >= '184500074'
and serial_no <= '184500076'
group by serial_no
) B
where 1 = 1
and A.register_date = B.date
)BB
where 1=1
and AA.serial_no = BB.serial_no
not working or working 600 sec
The query below uses explicit join syntax and case expressions to make you query easier to understand:
SELECT
COUNT( CASE WHEN ant_return_loss_pass = 'pass' AND
ant_cross_isolation_pass = 'pass' THEN 1 END ) AS pass_count
, COUNT( CASE WHEN ant_return_loss_pass = 'fail' AND
ant_cross_isolation_pass = 'fail' THEN 1 END ) AS fail_count
, COUNT( CASE WHEN ant_return_loss_pass = '' AND
ant_cross_isolation_pass = '' THEN 1 END ) AS blank_count
FROM (
SELECT
A.serial_no
, A.pass_fail AS ant_return_loss_pass
FROM ant_return_loss A
INNER JOIN (
SELECT MAX( register_date ) AS date
FROM ant_return_loss
WHERE serial_no >= '184500074'
AND serial_no <= '184500076'
GROUP BY serial_no
) B ON A.register_date = B.date
) AA
INNER JOIN (
SELECT
A.serial_no
, A.pass_fail AS ant_cross_isolation_pass
FROM ant_cross_isolation A
INNER JOIN (
SELECT MAX( register_date ) AS date
FROM ant_cross_isolation
WHERE serial_no >= '184500074'
AND serial_no <= '184500076'
GROUP BY serial_no
) B ON A.register_date = B.date
) BB ON AA.serial_no = BB.serial_no
To examine if this can be improved for performance however requires access to your database. For example do you indexes for ant_return_loss.serial_no or ant_cross_isolation.serial_no these will aid the where clauses of the subqueries.
Have you run any explain plans on the query? see: https://dev.mysql.com/doc/refman/5.7/en/explain.html
Note to avoid long running time you can use explain on separated portions of the overall query, look for indexes that may assist: e.g.
explain
SELECT MAX( register_date ) AS date
FROM ant_return_loss
WHERE serial_no >= '184500074'
AND serial_no <= '184500076'
GROUP BY serial_no
then:
explain
SELECT
A.serial_no
, A.pass_fail AS ant_return_loss_pass
FROM ant_return_loss A
INNER JOIN (
SELECT MAX( register_date ) AS date
FROM ant_return_loss
WHERE serial_no >= '184500074'
AND serial_no <= '184500076'
GROUP BY serial_no
) B ON A.register_date = B.date
until you have examined all portions for way to improve performance.
I am trying to collaborate 3 queries to perform arithmetic operation. The queries are shown in
(SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
FROM INVENTORY_ITEM
WHERE COMPANY_ID = 1
AND INVENTORY_ITEM.COMPANY_BRANCH_ID = 1
AND INVENTORY_ITEM.INV_ITEM_STATUS = 'Inward'
AND GRN_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY INVENTORY_ITEM.ITEM_ID) -
(SELECT ITEM_ID, SUM ( TOTAL_LITRE )
FROM STOCK_REQUISITION_ITEM B, STOCK_REQUISITION A
WHERE A.ID = B.REQUISITION_ID
AND A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID) +
(SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
FROM STOCK_RETURN_ITEM B, STOCK_RETURN A
WHERE A.ID = B.STOCK_RETURN_ID
AND A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID)
I am getting this error.
[Err] 42000 - [SQL Server]Incorrect syntax near '-'.
42000 - [SQL Server]Incorrect syntax near '+'
Not much to go on here for details. And we aren't actually sure if you are using mysql or sql server but pretty sure you are using sql server. I think you can accomplish what you are trying to do with something along these lines.
with Iventory as
(
SELECT i.ITEM_ID
, GoodQty = ISNULL(SUM(i.REC_GOOD_QTY), 0)
FROM INVENTORY_ITEM i
WHERE COMPANY_ID = 1
AND i.COMPANY_BRANCH_ID = 1
AND i.INV_ITEM_STATUS = 'Inward'
AND i.GRN_DATE < '2017-01-10'
GROUP BY i.ITEM_ID
)
, StockRequisition as
(
SELECT ITEM_ID
, TotalLitre = SUM(TOTAL_LITRE)
FROM STOCK_REQUISITION_ITEM B
JOIN STOCK_REQUISITION A ON A.ID = B.REQUISITION_ID
WHERE A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < '2017-01-10'
GROUP BY B.ITEM_ID
)
StockReturn as
(
SELECT ITEM_ID
, ReturnQuantity = SUM(RETURN_QUANTITY)
FROM STOCK_RETURN_ITEM B
JOIN STOCK_RETURN A ON A.ID = B.STOCK_RETURN_ID
WHERE A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= '2017-01-10'
GROUP BY B.ITEM_ID
)
select i.ITEM_ID
, MyCalculation = i.GoodQty - isnull(Req.TotalLitre, 0) + isnull(sr.ReturnQuantity, 0)
from Inventory i
left join StockRequisition sr on sr.ITEM_ID = i.ITEM_ID
left join StockReturn Req on Req.ITEM_ID = i.ITEM_ID
In your queries you always returns two fields ITEM_ID and a numeric field.
To apply an arithmetical operation you must return one numeric field
The first query:
SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
becomes
SELECT ISNULL(SUM(REC_GOOD_QTY),0)
The second query:
SELECT ITEM_ID, SUM ( TOTAL_LITRE )
becomes
SELECT SUM ( TOTAL_LITRE )
The third query:
SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
becomes
SELECT SUM ( RETURN_QUANTITY )
So the GROUP BY returns more than one row per query
UPDATE
i try to rewrite your query:
SELECT DISTINCT ii.item_id,
ISNULL(
(SELECT SUM(ii2.rec_good_qty)
FROM inventory_item ii2
WHERE ii2.item_id = ii.item_id
AND ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) -
ISNULL(
(SELECT SUM(total_litre)
FROM stock_requisition_item b
JOIN stock_requisition a
ON a.id = b.requisition_id
WHERE a.company_id = 1
AND a.req_from_branch_id = 1
AND a.requisition_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) +
ISNULL(
(SELECT SUM(return_quantity)
FROM stock_return_item b
JOIN stock_return a
ON a.id = b.stock_return_id
WHERE a.company_id = 1
AND a.company_branch_id = 1
AND a.return_date <= CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) AS result
FROM inventory_item ii
WHERE ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME)
I have a table like this:
<table border="1" cellspacing="0" cellpadding="5">
<tr><td>ID</td><td>status</td><td>start_date</td><td>end_date</td></tr>
<tr><td>1</td><td>A</td><td>2015-01-01</td><td>2015-12-31</td></tr>
<tr><td>1</td><td>B</td><td>2016-01-01</td><td>NULL</td></tr>
<tr><td>2</td><td>C</td><td>NULL</td><td>2016-12-31</td></tr>
<tr><td>3</td><td>D</td><td>NULL</td><td>NULL</td></tr>
</table>
I must do a trigger in MySQL to update a main table with the last status of a subject.
To do this I must select for every ID the last status based on the period between start_date and end_date that can be NULL if didn't known.
I write this SQL statement test:
SELECT *
FROM My_Table AS T
WHERE T.start_date Is Null AND
T.end_date In(SELECT MAX(end_date) FROM My_Table WHERE ID = T.ID)
OR
T.start_date In(SELECT MAX(start_date) FROM My_Table WHERE ID = T.ID) AND
T.end_date Is Null
OR
T.start_date In(SELECT MAX(start_date) FROM My_Table WHERE ID = T.ID) AND
T.end_date In(SELECT MAX(end_date) FROM My_Table WHERE ID = T.ID
);
Is there a shorten method to do this?
In practice I want a WHERE clause that catch each of these cases (a = start_date, b=end_date):
a = MAX AND b = MAX OR
a = NULL AND b = MAX OR
a = MAX AND b = NULL OR
a = NULL AND b = NULL
Here's a slightly simplified query which returns exactly the same result set as the query in your question. It uses only two subqueries instead of four (no duplicated subqueries):
SELECT *
FROM My_Table AS T
WHERE
(T.start_date Is Null OR T.start_date = (SELECT MAX(start_date) FROM My_Table WHERE ID = T.ID)) AND
(T.end_date Is Null OR T.end_date = (SELECT MAX(end_date) FROM My_Table WHERE ID = T.ID)) AND
(T.start_date Is NOT Null OR T.end_date Is NOT Null)
;
Note that it does NOT include the a = NULL AND b = NULL case. To include it as well, the last AND-clause must be removed, i.e.:
SELECT *
FROM My_Table AS T
WHERE
(T.start_date Is Null OR T.start_date = (SELECT MAX(start_date) FROM My_Table WHERE ID = T.ID)) AND
(T.end_date Is Null OR T.end_date = (SELECT MAX(end_date) FROM My_Table WHERE ID = T.ID))
;
I am using Laravel 5.1 in my application.
My MySQL Query is
SELECT * FROM (SELECT uu.*,t.left_id AS meb_id,(CAST(t.pair AS UNSIGNED) - IFNULL(p.pair,0)) AS pair FROM (SELECT left_id,
(CASE
WHEN ((SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000') >= (SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000')*2)
THEN (SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000')
WHEN ((SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000') < (SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000')*2)
THEN ((SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000') /2)
WHEN ((SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000') >= (SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000')*2)
THEN (SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000')
WHEN ((SELECT COUNT(meb_id) FROM user_count WHERE right_id=u.left_id AND active = 1 AND join_date <= '1442255400000') < (SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000')*2)
THEN ((SELECT COUNT(meb_id) FROM user_count WHERE left_id=u.left_id AND active = 1 AND join_date <= '1442255400000') / 2) END
) AS pair
FROM user_count AS u WHERE left_id <> 0 GROUP BY left_id) AS t
LEFT JOIN users AS uu ON uu.`id` = t.left_id
LEFT JOIN `total_payment` p ON t.left_id = p.`meb_id`
WHERE t.pair <> 0) AS f WHERE f.pair > 0 AND f.active = 1
How Can I convert it in Laravel Eloquent? I don't know how to use when case in laravel eloquent.
My Database schema is like this
user_count table
user table
total_payment table
Can anyone help me please?
Just surround your raw query with a DB::statement(""), like this :
DB::statement("INSERT INTO `mydatabase`.`mytable` (`id`, `created_at`, `updated_at`, `deleted_at`) VALUES ('7', '2015-09-26 13:38:48', '2015-09-26 13:43:41', NULL)");
It will do the job fine and works with seeds as well.
Eloquent is an ORM (Object-relational mapping), it means you can map your database to PHP objects (Eloquent use the Active Record pattern).
It is not a DBAL however you can still execute SQL queries through the DB Facade.
The example provided by you, the user table can be an Eloquent object.
class User extends Model{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'user';
}
Since now you can fetch all user rows like:
$userCollection = (new User)->all(); //Fetch all rows
Or you can find one by PK like:
$user = (new User)->find(123); //123 is the PK of the User