How to subtract two calculated fields from the same table in MySQL? - mysql

SELECT *,
SUM(price+shipping+paypalfee+storefee) AS totalcost,
customerpaid AS totalrevenue,
(totalcost - totalrevenue) AS profit
FROM tblsales
GROUP BY orderno
HAVING " . $having . "
ORDER BY $sort $order
LIMIT $offset,$rows
If I omit (totalcost - totalrevenue) as profit the query works fine. How could I calculate PROFIT in the same query using totalcost and totalrevenue?

The answer to your question is that you have to repeat the expressions:
select *, sum(price+shipping+paypalfee+storefee) as totalcost
customerpaid as totalrevenue,
(sum(price+shipping+paypalfee+storefee) - customerpaid) as profit
from tblsales
group by orderno
having " . $having . "
order by $sort $order
limit $offset, $rows;
You are not allowed to use a column alias in the same select where it is defined.
And, your query looks weird. Any query that has select * and group by is suspect. You have many columns (presumably) whose value will come from an indeterminate row for each group. You should explicitly list the columns in general, but you should especially do so for a group by.

You can do like this
SELECT * , (totalcost - totalrevenue) AS profit FROM(
SELECT *,
SUM(price+shipping+paypalfee+storefee) AS totalcost,
customerpaid AS totalrevenue,
FROM tblsales
GROUP BY orderno
HAVING " . $having . "
ORDER BY $sort $order )
LIMIT $offset,$rows

Related

How we concatenate numeric result with a string in SQL

I want to concatenate a result of float with a string object in MySQL
interface,
I wrote this query:
select name, concat(str(round(sum(amount_paid)/(select sum(amount_paid) from order_items)*100.0,2)) ,'%') as pct
from order_items
group by 1
order by 2 desc;
Can anyone give me a reliable query, as it seems I am missing something.
str() is not a thing in MySQL. concat() forces the conversion to string, so you can just do:
select name,
concat(
round(
sum(amount_paid) / (select sum(amount_paid) from order_items) * 100,
2
),
'%'
) as pct
from order_items
group by name
order by pct desc;
Note that if you are running MySQL 8.0, you can make use of a window sum instead of a subquery:
select name,
concat(
round(
sum(amount_paid) / sum(sum(amount_paid)) over() * 100,
2
),
'%'
) as pct
from order_items
group by name
order by pct desc;

Mysql count query by Grouping Year and Month horizontal

I am new to mysql query and i am stuck on getting query. Basically, i want the date to group as Year and month (Jan'17, Feb'17...) in horizontal way (column) as shown in Image below.
Data are shown in image below:
Please help to create query.
You can do conditional aggregation - once per login_id and then overall and then union both the results.
Select login_idindex,
Sum(date_format(visitdate, '%Y%m') = '201701' ) as jan_17,
Sum(date_format(visitdate, '%Y%m') = '201702' ) as feb_17,
. . .,
Count(*) as total
From your_table
Where visitdate between ? and ?
Group by login_idindex
Union all
Select null,
Sum(date_format(visitdate, '%Y%m') = '201701' ) as jan_17,
Sum(date_format(visitdate, '%Y%m') = '201702' ) as feb_17,
. . .,
Count(*) as total
From your_table
Where visitdate between ? and ?;
Replace ? with actual dates or remove the where clause if you are working with all the dates.

How to create RUNNING TOTAL in this mysql query

select saleid, orderno, orderdate,
sum(purchaseprice+purchaseshipping+paypalfee+storefee) as totalcost,
customerpaid as totalrevenue,
(customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) as profit,
ROUND((((customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) / customerpaid) * 100.00),2) as profitmargin
from tblsales
group by orderno having " . $having . "
order by $sort $order limit $offset,$rows
This query works fine. Is there a way to add running total profit field to this query that performs a running sum of profit already calculated in the query?
Just put it in a subquery and use variables:
select t.*,
(#cumesum := #cumesum + profit) as runningprofit
from (select saleid, orderno, orderdate,
sum(purchaseprice+purchaseshipping+paypalfee+storefee) as totalcost,
customerpaid as totalrevenue,
(customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) as profit,
ROUND((((customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) / customerpaid) * 100.00),2) as profitmargin
from tblsales
group by orderno
having " . $having . "
) t cross join
(select #cumesum := 0) vars
order by $sort $order
limit $offset, $rows;

Where to put WHERE in mysql query

I cannot find where I can put my WHERE clause in my query. It seems like I tried every possible position but nothing is working.
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) a
ORDER BY `date` ASC
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
I'd have thought you need to put it after the FROM clause in the subquery:
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) a
ORDER BY `date` ASC
You can see this order documented in the MySQL manual.
It seems that you are using an inner query in your clause. You made some mistakes. Try this:
SELECT res
FROM
(
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) inner query
ORDER BY `date` ASC
Usually, I find including your WHERE clause before the ORDER and GROUP clauses is best:
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
)
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
ORDER BY `date` ASC

Order of "id" changed in subquery?

I have this query
SELECT bul.id
FROM bul
WHERE id IN (SELECT hotid AS parentid
FROM likehot
WHERE hotid IN (SELECT id
FROM bul
WHERE DATE >= '1315976410')
GROUP BY hotpid
ORDER BY COUNT( hotid ) DESC )
when I runt this inner query
SELECT id
FROM bul
WHERE DATE >= '1315976410')
GROUP BY hotpid
ORDER BY COUNT( hotid ) DESC
I get
parentid
3655
3656
3622
3644
and when I run whole query I get
parentid
3656
3655
3622
3644
I really don't understand why the order of the ids change?
SOLUTION :-
<?php
$query_hotpress_like = "SELECT hotid AS parentid FROM likehot WHERE hotid IN (SELECT id FROM bul WHERE DATE >= '" . (time() - (24 * 60 * 60)) . "') GROUP BY hotid ORDER BY COUNT( hotid ) DESC";
$exe_hotpress_like = execute_query($query_hotpress_like, true, "select");
$temp_like1 = array();
foreach ($exe_hotpress_like as $kk => $exe_like) {
$temp_like1[] = "'" . $exe_like['parentid'] . "'";
}
$temp_like = str_replace(",''", "", implode(',', $temp_like1));
$query_hotpress = "SELECT bul.id,photo_album_id,eventcmmnt_id,link_url,youtubeLink,link_image,id, mem_id, subj, body, bul.date,parentid, from_id, visible_to,image_link,post_via FROM bul WHERE id IN ($temp_like) ORDER BY FIELD(id,$temp_like ) LIMIT 5";
?>
execute_query() is the inbuilt function to get the result of query.
That happens because for IN operator order doesn't matter.
If you need to sort outer query - sort outer query.
Since you didn't specify an order for the "whole" query, the database is at liberty to return rows in any order it wants. The specific order you get is a result of how looking up rows is done when using the IN operator.
On your other query you are specifying an order yourself, so the database has to honor it.