MYSQL retrieve data dependent on rows returned - mysql

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

Related

Get Multi Columns Count in Single Query

I am working on a application where I need to write a query on a table, which will return multiple columns count in a single query.
After research I was able to develop a query for a single sourceId, but what will happen if i want result for multiple sourceIds.
select '3'as sourceId,
(select count(*) from event where sourceId = 3 and plateCategoryId = 3) as TotalNewCount,
(select count(*) from event where sourceId = 3 and plateCategoryId = 4) as TotalOldCount;
I need to get TotalNewCount and TotalOldCount for several source Ids, for example (3,4,5,6)
Can anyone help, how can I revise my query to return a result set of three columns including data of all sources in list (3,4,5,6)
Thanks
You can do all source ids at once:
select source_id
sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event
group by source_id;
Use a where (before the group by) if you want to limit the source ids.
Note: The above works in both Vertica and MySQL, and being standard SQL should work in any database.

MySQL: get sum of columns with multiply two columns on behalf of third column

I am trying to get sum of all rows with multiply two column values with where condition but getting some error of mysql. After try some example i achieve my result but i don't know that is right way or not:
Table: store_stocks
i just want to count the stock qty with amount multiply with qty according to with VAT, with non VAT and total stock.
I just created that query:
SELECT sum(qty*sale_price) as total_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 0 and store_id = 8) as non_vat_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 1 and store_id = 8) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
and its showing result:
can any one tell me is there any another way to achieve this, because i think that's query is little bit complicated, each time i am using where in sub query and i also have to implement this query in laravel eloquent.
You do not need subqueries, you can use a condition within the sum() to make it summarise the specific records only:
SELECT sum(qty*sale_price) as total_stock,
sum(if(vat_status = 0, qty*sale_price, 0)) as non_vat_stock,
sum(if(vat_status = 1, qty*sale_price, 0)) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
You can use a case expression instead of the if() function as well.

MYSQL Select single row by multiple parameters returning unexpected result

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.

MySQL MAX from count query

I have table rozpis_riesitelov which contains columns :
id_rozpisu_riesit, id_zam, id_projektu, id_ulohy.
I made query :
select id_zam, id_ulohy, count(*) as counted
from rozpis_riesitelov
group by id_zam
having id_ulohy in (1,2,8)
which shows me id of employee (id_zam) and how many times He was in project (id_ulohy is irrevelant but I had to select it beacuse of having clause). It shows me everyone in db but I am looking for employee with ID of 4 who is in 6 projects (Yes, I could do order by but I want to see max). When I do max of this query like this:
select max(counted)
from (select id_zam, id_ulohy, count(id_zam) as counted
from rozpis_riesitelov
group by id_zam
having id_ulohy in (1,2,8)) as riesitel
which shows me number 149 instead of 6.
So basically I only need to find employee that occurs in the most of the projects.
What's wrong with sorting by the COUNT() value, and limiting to one result?
SELECT `id_zam`,
`id_ulohy`,
COUNT(*) AS `counted`
FROM `rozpis_riesitelov `
WHERE `id_ulohy` IN ( 1, 2, 8 )
GROUP BY `id_zam`
ORDER BY `counted` DESC
LIMIT 1
Not sure exactly what you are trying to accomplish but you only use HAVING to filter on your aggregate like this:
HAVING COUNT(*) > 1
you should be able to move the condition to a WHERE clause and get correct max returned:
select max(counted)
from (select id_zam, count(id_zam) as counted
from rozpis_riesitelov
where id_ulohy in (1,2,8)
group by id_zam) as riesitel

Sql query to sum up total of columns previously used aggregate function

From this post, enter link description here
I would like to improve the query
SELECT `BetType`,
count(`BetType`) AS COUNT,
sum(`BetAmount`) AS BetAmountTotal,
sum(`Payout`) AS PayoutTotal
FROM `betdb`
LEFT JOIN `matchdb` ON `betdb`.`MatchID` = `matchdb`.`MatchID`
WHERE `betdb`.`MatchID`=135
GROUP BY `BetType`
thanks to Sadikhasan, who helped on this query
I would like to add another row showing the totals of the columns
BetType Count BetAmount Total Payout Total
Handi 2 60000 950000
Homerun Count 4 10000 0
Total 6 70000 950000
this seems to be needing another SELECT statement but how would I put another row explicitly showing the "Total" string and getting the sum of the previously used columns with Aggregate Functions?
You can use WITH ROLLUP modifier to GROUP BY, which will give you another row with totals, but the column you group on (BetType) will show NULL for that row. But nothing stops you from using COALESCE() to replace that NULL with 'Total' string.
SELECT COALESCE(`BetType`,'Total') AS BetType,
COUNT(*) AS `Count`,
sum(BetAmount) AS BetAmountTotal,
sum(Payout) AS PayoutTotal
FROM betdb
WHERE betdb.MatchID=135
GROUP BY BetType WITH ROLLUP