MYSQL Select single row by multiple parameters returning unexpected result - mysql

I have a table offers with five relevant columns, offer_id, offer_type, offer_amount, end_date and offer_status
I am trying to select the row with the highest offer_amount that matches the correct offer_type and an offer_status of 1 (active).
The query I am using is
SELECT * FROM offers_tbl WHERE offer_status = 1 AND offer_type = 'site-wide' AND offer_amount = (SELECT MAX(offer_amount) FROM offers_tbl )
Whats happening is that this is not returning any results if the MAX(offer_amount) happens to have a offer_status of 0 (inactive).
If the particular row with the highest MAX(offer_amount) happens to have an offer_status of 1, this works fine. Its only when the offer status is 0 that this breaks.

Try making it find MAX out of active ones:
SELECT * FROM offers_tbl WHERE offer_status = 1 AND offer_type = 'site-wide' AND offer_amount = (SELECT MAX(offer_amount) FROM offers_tbl WHERE offer_status = 1)
Otherwise, it's finding MAX offer amounts that could have a status of 0, which makes the outside query not find a match of status of 1 AND that amount.

Related

mysql select counts by if else condition

i have a table named cq500_all(to record diffrent doctor feedback)
now i want know counts when condition status is
field dr_1_finish and field dr_2_finish value is all fill 1
and
when field dr_1 different dr_2 (like dr_1=1 and dr_2=0,or dr_1=0 and dr_2=1 )
cause i want to know two doctors feedback counts (when different doctor's feedback on jpg)
for example image show CQ500-CT-1_36_08.jpg and CQ500-CT-1_36_09.jpg is match my select counts
it will be two (select counts result)
how to make the query on mysql?
You can count as
select count(*) as total
from cq500_all
where dr_1_finish = 1 and dr_2_finish = 1 and dr_1 != dr_2
You will got result in total
Pretty much just the way you've described it:
select *
from cq500_all
where dr_1_finish = 1 and dr_2_finish = 1
and dr_1 != dr_2
or (if dr_1 or dr_2 might not be just 0 and 1):
select *
from cq500_all
where dr_1_finish = 1 and dr_2_finish = 1
and ((dr_1 = 1 and dr_2 = 0) or (dr_1 = 0 and dr_2 = 1))

query optimization for mysql

I have the following query which takes about 28 seconds on my machine. I would like to optimize it and know if there is any way to make it faster by creating some indexes.
select rr1.person_id as person_id, rr1.t1_value, rr2.t0_value
from (select r1.person_id, avg(r1.avg_normalized_value1) as t1_value
from (select ma1.person_id, mn1.store_name, avg(mn1.normalized_value) as avg_normalized_value1
from matrix_report1 ma1, matrix_normalized_notes mn1
where ma1.final_value = 1
and (mn1.normalized_value != 0.2
and mn1.normalized_value != 0.0 )
and ma1.user_id = mn1.user_id
and ma1.request_id = mn1.request_id
and ma1.request_id = 4 group by ma1.person_id, mn1.store_name) r1
group by r1.person_id) rr1
,(select r2.person_id, avg(r2.avg_normalized_value) as t0_value
from (select ma.person_id, mn.store_name, avg(mn.normalized_value) as avg_normalized_value
from matrix_report1 ma, matrix_normalized_notes mn
where ma.final_value = 0 and (mn.normalized_value != 0.2 and mn.normalized_value != 0.0 )
and ma.user_id = mn.user_id
and ma.request_id = mn.request_id
and ma.request_id = 4
group by ma.person_id, mn.store_name) r2
group by r2.person_id) rr2
where rr1.person_id = rr2.person_id
Basically, it aggregates data depending on the request_id and final_value (0 or 1). Is there a way to simplify it for optimization? And it would be nice to know which columns should be indexed. I created an index on user_id and request_id, but it doesn't help much.
There are about 4907424 rows on matrix_report1 and 335740 rows on matrix_normalized_notes table. These tables will grow as we have more requests.
First, the others are right about knowing better how to format your samples. Also, trying to explain in plain language what you are trying to do is also a benefit. With sample data and sample result expectations is even better.
However, that said, I think it can be significantly simplified. Your queries are almost completely identical with the exception of the one field of "final_value" = 1 or 0 respectively. Since each query will result in 1 record per "person_id", you can just do the average based on a CASE/WHEN AND remove the rest.
To help optimize the query, your matrix_report1 table should have an index on ( request_id, final_value, user_id ). Your matrix_normalized_notes table should have an index on ( request_id, user_id, store_name, normalized_value ).
Since your outer query is doing the average based on an per stores averages, you do need to keep it nested. The following should help.
SELECT
r1.person_id,
avg(r1.ANV1) as t1_value,
avg(r1.ANV0) as t0_value
from
( select
ma1.person_id,
mn1.store_name,
avg( case when ma1.final_value = 1
then mn1.normalized_value end ) as ANV1,
avg( case when ma1.final_value = 0
then mn1.normalized_value end ) as ANV0
from
matrix_report1 ma1
JOIN matrix_normalized_notes mn1
ON ma1.request_id = mn1.request_id
AND ma1.user_id = mn1.user_id
AND NOT mn1.normalized_value in ( 0.0, 0.2 )
where
ma1.request_id = 4
AND ma1.final_Value in ( 0, 1 )
group by
ma1.person_id,
mn1.store_name) r1
group by
r1.person_id
Notice the inner query is pulling all transactions for the final value as either a zero OR one. But then, the AVG is based on a case/when of the respective value for the normalized value. When the condition is NOT the 1 or 0 respectively, the result is NULL and is thus not considered when the average is computed.
So at this point, it is grouped on a per-person basis already with each store and Avg1 and Avg0 already set. Now, roll these values up directly per person regardless of the store. Again, NULL values should not be considered as part of the average computation. So, if Store "A" doesn't have a value in the Avg1, it should not skew the results. Similarly if Store "B" doesnt have a value in Avg0 result.

Is it possible to 'concat' two different COUNT(column) WHERE column can have two differen values and different total?

I come with this problem in a kinda complex query to me. Let me be more clear with an example.
If I have a banner table which stores all the banners on a site and I have another table called banner_statistics which stores a record for each banner event in a particular period of time (the event can be 'I', which means an impression of the banner and 'C', which means a click on a banner).
If I run this query:
-- Count number of impressions of the banner with id = 1
SELECT
ban_id,
ban_url,
COUNT(bansta_event) as num_impressions
FROM banner
LEFT JOIN banner_statistics
ON bansta_ban_id = ban_id
AND bansta_event = 'I'
WHERE ban_id = 1
I get:
ban_id ban_url num_impressions
1 http://www.cocacola.com 7
It says that the banner with id = 1 which is a cocacola banner had a total of 7 impressions.
If I run the same query with the 'C' (click event on that banner):
-- Count number of impressions of the banner with id = 1
SELECT
ban_id,
ban_url,
COUNT(bansta_event) as num_impressions
FROM banner
LEFT JOIN banner_statistics
ON bansta_ban_id = ban_id
AND bansta_event = 'C'
WHERE ban_id = 1
I get:
ban_id ban_url num_clicks
1 http://www.cocacola.com 1
It says that this banner had only one click
Now how can I merge those results into a single query in order to obtain this result:
ban_id ban_url num_impressions num_clicks
1 http://www.cocacola.com 7 1
Is there a way to do it? It seems like a CONCAT but it's not cause it is the result of another query with a COUNT on the same column but where the condition on what to count on that column is different...
How can I achieve this in MySQL? I have found that there is GROUP_CONCAT but it can't receive the result of a SELECT query as param, and I don't think that it can work in my case...
Try this:
SELECT
ban_id,
ban_url,
IFNULL(SUM(bansta_event = 'C'), 0) as num_impressions,
IFNULL(SUM(bansta_event = 'I'), 0) as num_clicks
FROM banner
LEFT JOIN banner_statistics
ON bansta_ban_id = ban_id
AND bansta_event IN ('I', 'C')
WHERE ban_id = 1
In MySQL, comparison operators return 1 when they match, 0 when they don't. So summing them gets the count of rows that match that criteria. The IFNULL is needed in case there are no rows that match that the criteria, so we get 0 instead of NULL in the results.

MYSQL retrieve data dependent on rows returned

I am working on a mysql query that will filter out certain occurrences dependent on how many rows are returned.
I am trying to filter out any support categories when the number of rows returned are 1, however leave the support category in when the result set turned is more than 1.
I originally had this idea however it seems as if it will not work.
SELECT stockmaster.description, SUM(salesorderdetails.quantity), stockmaster.categoryid as qty
FROM salesorderdetails, stockmaster
where salesorderdetails.stkcode=stockmaster.stockid
and orderno='5222'
group by stockmaster.description
HAVING CASE WHEN stockmaster.categoryid = 'S&M' THEN COUNT(*) >= 2 ELSE COUNT(*) = 1 END
Any help will be gratefully accepted.
Try this
SELECT *
FROM
(
SELECT stockmaster.description,
SUM(salesorderdetails.quantity),
stockmaster.categoryid as qty ,
COUNT(*) AS count
FROM salesorderdetails, stockmaster
where salesorderdetails.stkcode=stockmaster.stockid
and orderno='5222'
group by stockmaster.description
HAVING CASE WHEN stockmaster.categoryid = 'S&M'
) MAIN_DATA
WHERE MAIN_DATA.count >1

how can I tell if the last x rows of 'state' = 1

I need help with a SQL query.
I have a table with a 'state' column. 0 means closed and 1 means opened.
Different users want to be notified after there have been x consecutive 1 events.
With an SQL query, how can I tell if the last x rows of 'state' = 1?
If, for example, you want to check if the last 5 consecutive rows have a state equals to 1, then here's you could probably do it :
SELECT IF(SUM(x.state) = 5, 1, 0) AS is_consecutive
FROM (
SELECT state
FROM table
WHERE Processor = 3
ORDER BY Status_datetime DESC
LIMIT 5
) as x
If is_consecutive = 1, then, yes, there is 5 last consecutive rows with state = 1.
Edit : As suggested in the comments, you'll have to use ORDER BY in your query, to get the last nth rows.
And for more accuracy, since you have a timestamp column, you should use Status_datetime to order the rows.
You should be able to use something like this (replace the number in the HAVING with the value of x you want to check for):
SELECT Processor, OpenCount FROM
(
SELECT TOP 10 Processor, DateTime, Sum(Status) AS OpenCount
FROM YourTable
WHERE Processor = 3
ORDER BY DateTime DESC
) HAVING OpenCount >= 10