Multiple Select with same table in MySQL doesn't work - mysql

i'm having a problem with my database's multiple selection. I need to do a select that returns a kind of table with some processed data, and it need to be ordered by day of month. To do this, i'm using multiple select's issue of mysql. This is my code:
SELECT
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 AS 'Total',
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `status` = 0 and `status_cancel` = 0 AS 'Open',
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `status_cancel` = 1 AS 'Cancel',
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `date_finish` is not null and `status_cancel` = 0 AS 'Finish',
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `result` >= 0 and `date_finish` is not null and `status_cancel` = 0 AS 'Win',
(SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `result` < 0 and `date_finish` is not null and `status_cancel` = 0 AS 'Loss'
Now it's returning the total of all rows in my table, but i can't do this return it grouped by day, help me, please!
The result must be like this:
Result that i need

I think you are saying how can I group by date when my queries are all amounting to sub queries. I would change it to be case statements for that. Try something like this
SELECT DATE(date_finish) as `date`, count(*) as 'Total',
SUM(CASE WHEN `status` = 0 AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Open',
SUM(CASE WHEN `status_cancel` = 1 THEN 1 ELSE 0 END) as 'Cancel',
SUM(CASE WHEN `date_finish` is not null and `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Finish',
SUM(CASE WHEN `result` >= 0 AND `date_finish` is not null AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Win',
SUM(CASE WHEN `result` < 0 AND `date_finish` is not null AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Loss'
from `table`
WHERE `type` = 1
group by DATE(date_finish)
TEST: http://rextester.com/HCRIU11065

Related

order by not working on alias column in mysql query with union all query

SELECT SUM(T1.approve_con) AS compl_rec,
SUM(T1.payout) AS payout,
SUM(T1.reversal) AS reversal,
T1.app_id,
T1.end_user,
T1.created
FROM (
(SELECT app_id,end_user,created,
approve_conversions AS `approve_con`,
'0' AS reversal,
payout AS payout
FROM app_end_users
WHERE publisher_id=1625
AND app_id=57)
UNION ALL
(SELECT opinongold_survey_response.app_id,
opinongold_survey_response.user_id AS end_user,
opinongold_survey_response.movement AS created,
(CASE WHEN opinongold_survey_response.survey_status= 'Completed' THEN 1 ELSE 0 END) AS `approve_con`,
(CASE WHEN opinongold_survey_response.survey_status= 'Rejected' THEN 1 ELSE 0 END) AS reversal,
(CASE WHEN opinongold_survey_response.survey_status= 'Completed' THEN payout ELSE 0 END) AS payout
FROM opinongold_survey_response
WHERE pub_id=1625
AND app_id=57)
) AS T1
GROUP BY T1.app_id,T1.end_user
ORDER BY `approve_con` DESC
LIMIT 0, 10
above is my mysql query order by is not working on approve_con, payout, reversal column
please let me where i am doing wrong in this query.

Explain me ways to understand this complex query

Can anyone help me to understand this big sql query. How do I break it down in small chunks to understand it ?
select t.Instrument as Instrument ,ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,SettlePrice,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
ISNULL(PrevQty +TodayBuyQty-TodaySellQty,0) as NetQty,
TodayBuyPrice, TodaySellPrice,LTP,PnL,Token
from
(
select Instrument,w.ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
TodayAvgBuyPrice as TodayBuyPrice,TodayAvgSellPrice as TodaySellPrice,
LTP,PnL,w.Token
from
(
select Symbol as Instrument, ClearingId,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
TodayAvgBuyPrice,
ISNULL( -TodaySellQty ,0) AS TodaySellQty,
TodayAvgSellPrice, NULL as LTP ,NULL as PnL ,
w.Token as Token
from
(
select Token, sum(Qty) as NetPositionQty, ClearingId,
sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END) as TodaySellQty,
sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END) as TodayBuyQty,
sum(CASE WHEN Qty < 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END), 0) as TodayAvgSellPrice,
sum(CASE WHEN Qty > 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END), 0) as TodayAvgBuyPrice
from
(
select m.Token,
(CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Strategy_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select m.Token, (CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,
Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Manual_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select Token , ClearingId , TodayBuyPrice ,
TodayBuyQty as Qty
from EOD_Holdings
where CurrentDate =
( select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
UNION ALL
select Token , ClearingId , TodaySellPrice ,
TodaySellQty as Qty
from EOD_Holdings
where CurrentDate = (
select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
) x
group by Token,ClearingId) w
JOIN(select Token, Symbol from TokenMAp ) h on w.Token = h.Token
) w
FULL OUTER JOIN(
select Token, PrevQty , ClearingId
from EOD_Holdings
where CurrentDate = ( select top 1 CurrentDAte from EOD_Holdings order by CurrentDAte desc
)
) h
on w.Token = h.Token and w.ClearingId = h.ClearingId
)t
JOIN (
select * from LatestSettlePrices
) sp
on t.Instrument = sp.Instrument
You can break the query into chunks by looking at each subquery ("select ..." ) separately and running them to see the results. You need to start with the innermost queries that do not have other select statements in the "from" or "where" clause.
Also note that this query does not seem to be a clear, neither an optimal solution.
You would want to avoid using full outer joins and union all statements for the best performance.

mysql sum case not working

I am working on a mysql query using sum case. The query works for some of the cases but not for one case.
select orders.orderid, campers.description, dealers.name, orders.act_delivery,
sum(case orderitems.std
when 0 then
(case when orderitems.price = 0 then retail_price.price * orderitems. qty else orderitems.price * orderitems.qty end)
when 1 then
(case when orderitems.origqty = 0 then
0 else
(case when orderitems.price = 0
then retail_price.price * (orderitems.qty - orderitems.origqty)
else orderitems.price * (orderitems.qty - orderitems.origqty)
end)
end)
when 2 then
0
else
(case when orderitems.deletedprice = 0 then retail_price.price * orderitems. qty else orderitems.deletedprice * orderitems.qty end)
end) as retail
from orderitems, orders, dealers, campers, products, retail_price
where orderitems.orderid = orders.orderid
and orderitems.productid = products.prodid
and orderitems.productid =retail_price.prodid
and orders.dealerid = retail_price.dealer
and orders.dealerid = dealers.dealerid
and orders.camper = campers.camperid
and act_delivery > 0
and orderitems.std in (0, 1, 2)
and orders.dealerid not in (1, 9, 10, 12,15,16)
and spares_od = 0
and orders.act_delivery > '2016-10-01'
and orders.act_delivery <= '2016-10-31'
group by orders.orderid,orders.dealerid, orders.act_delivery order by orders.act_delivery, orders.orderid
The problem occurs when orderitems.std = 3. In either case I cannot get a result.
All other cases appear to be working correctly.

Case When with AND?

I want to use Case When with AND condition and it is not calculating the sum properly.
For example:
SELECT DATE(`SubmitDate`),
SUM(CASE status WHEN 'New' AND `Type` = 'consumer' THEN 1 ELSE 0 END) as new_consumer,
SUM(CASE status WHEN 'New' AND `Type` = 'business' THEN 1 ELSE 0 END) as new_business
FROM report
WHERE `source` = 'net'
group by DATE(`SubmitDate`) Order by `SubmitDate` DESC
You need to use CASE WHEN [Condition] THEN... rather than a simple case expression:
SELECT DATE(`SubmitDate`),
SUM(CASE WHEN status = 'New' AND `Type` = 'consumer' THEN 1 ELSE 0 END) as new_consumer,
SUM(CASE WHEN status = 'New' AND `Type` = 'business' THEN 1 ELSE 0 END) as new_business
FROM report
WHERE `source` = 'net'
group by DATE(`SubmitDate`) Order by `SubmitDate` DESC
You should write
CASE WHEN status='New' AND `Type` = 'consumer' THEN 1 ELSE 0 END
Check the syntax of CASE WHEN

MySQL order rank as a column

I have a MySQL query that selects data from multiple tables and then orders the results based on some arbitrary criteria as below:
SELECT [columns] FROM (
SELECT *, COUNT(*) as `matches`
FROM [table1]
JOIN [table2] USING (id)
JOIN [table3] USING (id)
WHERE [criteria]
GROUP BY `id`
ORDER BY `matches` DESC
) AS `grouped`
ORDER BY (
(CASE WHEN [1st rank criteria] THEN 3 ELSE 0 END) +
(CASE WHEN [2nd rank criteria] THEN 2 ELSE 0 END) +
(CASE WHEN [3rd tank criteria] THEN 1 ELSE 0 END)
) DESC
LIMIT 100
This works fine, but my question is: can I have the ranking score displayed as a column? I've looked at trying to use variables, but I'm quite new to SQL so all this is a bit beyond me.
Sorry if this is an obvious question, but many thanks in advance for your time and assistance.
Try this:
SELECT [columns],
(
(CASE WHEN [1st rank criteria] THEN 3 ELSE 0 END) +
(CASE WHEN [2nd rank criteria] THEN 2 ELSE 0 END) +
(CASE WHEN [3rd tank criteria] THEN 1 ELSE 0 END)
) AS MyRank
FROM (
SELECT *, COUNT(*) as `matches`
FROM [table1]
JOIN [table2] USING (id)
JOIN [table3] USING (id)
WHERE [criteria]
GROUP BY `id`
ORDER BY `matches` DESC
) AS `grouped`
ORDER BY MyRank DESC
LIMIT 100;
put it in the select
((CASE WHEN [1st rank criteria] THEN 3 ELSE 0 END) +
(CASE WHEN [2nd rank criteria] THEN 2 ELSE 0 END) +
(CASE WHEN [3rd tank criteria] THEN 1 ELSE 0 END)) as ranking