MySQL: Comparing date using IF condition in SELECT statement - mysql

Sample data:
db1.locationDetails table
| id | locationUID | locationName |
|----|-------------|--------------|
| 1 | L0001 | Site A |
| 2 | L0002 | Site B |
| 3 | L0003 | Site C |
| 3 | L0004 | Site D |
db2.HealthData table
| id | locationID | Date_Time | memUsage |
|----|-------------|------------------|----------|
| 1 | L0001 | 2018-09-10 11:43 | 35 |
| 2 | L0002 | 2018-09-10 08:22 | 39 |
| 3 | L0003 | 2018-09-10 14:44 | 43 |
| 4 | L0004 | 2018-09-10 16:01 | 72 |
| 5 | L0001 | 2018-09-12 01:26 | 50 |
| 6 | L0002 | 2018-09-12 03:15 | 32 |
I have a query:
SELECT DISTINCT db1.locationDetails.locationUID,
db1.locationDetails.locationName,
MAX(db2.HealthData.Date_Time),
db2.HealthData.memUsage,
IF(DATE(db2.HealthData.Date_Time) = '2018-09-12', "ON", "OFF") AS Status
FROM db1.locationDetails
LEFT JOIN db2.HealthData
ON db1.locationDetails.locationUID = db2.HealthData.locationID
GROUP BY db1.locationDetails.locationUID
Based on my understanding, the 'Status' column will show "ON" if the Date is equals to 2018-09-12 but somehow it always returns "OFF" regardless of whether the value in the Date_Time column is equal to the Date value specified in the query.
Can anyone tell me what is wrong here? Thanks in advance.
Expected output:
| locationUID | locationName | Date_Time | memUsage | Status |
|-------------|--------------|-----------------|----------|--------|
| L0001 | Site A |2018-09-12 01:26 | 50 | ON |
| L0002 | Site B |2018-09-12 03:15 | 32 | ON |
| L0003 | Site C |2018-09-10 14:44 | 43 | OFF |
| L0004 | Site D |2018-09-10 16:01 | 72 | OFF |

Use subquery to get your desired result:
select x.locationuid,x.locationname,maxitme, memusage, case when date(maxtime)='2018-09-12' then 'ON' else 'OFF' end as status
from db1.locationDetails x
inner join
(select a.locationuid,maxtime,memusage
from
(SELECT locationUID,MAX(Date_Time) as maxtime FROM db2.HealthData group by locationUID)a
inner join db2.HealthData b on a.locationuid=b.locationuid)y
on x.locationuid=y.locationuid

add Group by db1.locationDetails.locationUID,db2.HealthData.id
SELECT DISTINCT db1.locationDetails.locationUID,
db1.locationDetails.locationName,
MAX(db2.HealthData.Date_Time),
db2.HealthData.memUsage,
IF(DATE(db2.HealthData.Date_Time) = '2018-09-12', "ON", "OFF") AS Status
FROM db1.locationDetails
LEFT JOIN db2.HealthData
ON db1.locationDetails.locationUID = db2.HealthData.locationID
GROUP BY db1.locationDetails.locationUID,db2.HealthData.id

Related

Find min value in column by grouping more than one column in sql

+----+-------+-----------------------------+-------------------------+-------------------+-------------+
| Id | grade | shot_name | submitted_by_supervisor | version_submitted | submit_type |
+----+-------+-----------------------------+-------------------------+-------------------+-------------+
| 27 | A | elx_reel01_scn1020_shot1720 | Salil Devji | 33 | Fresh |
| 27 | A | elx_reel01_scn1020_shot1720 | Deepali | 34 | Fresh |
| 37 | A | elx_reel01_scn1030_shot3480 | Salil Devji | 15 | Fresh |
| 37 | A | elx_reel01_scn1030_shot3480 | Salil Devji | 20 | Fresh |
| 7 | B | elx_reel01_scn1010_shot1030 | Darshan | 4 | Fresh |
| 7 | B | elx_reel01_scn1010_shot1030 | Varion | 6 | Fresh |
| 17 | B | elx_reel01_scn1010_shot1140 | Varion | 17 | Fresh |
| 17 | B | elx_reel01_scn1010_shot1140 | Varion | 14 | Fresh |
+----+-------+-----------------------------+-------------------------+-------------------+-------------+
I have column (submit_type) inserting new column in that value are set by CASE condition
here is my sql query :
SELECT s.shot_id,
s.shot_name ,
isn.reviewer AS 'submitted_by_supervisor',
isn.version AS 'version_submitted',
isn.grade AS 'grade',
CASE
WHEN isn.version = Min(isn.version) THEN 'FRESH'
ELSE 'Once Submitted'
end AS 'submit_type'
FROM viewd_elx.india_supe_note isn
JOIN viewd_elx.shot s
ON s.shot_id = isn.shot_id
JOIN viewd_elx.team t
ON isn.shot_id = t.shot_id
JOIN viewd_elx.viewd_team vt
ON isn.shot_id = vt.shot_id
WHERE isn.promoted='Yes'
AND isn.grade IN ('A',
'B')
GROUP BY isn.grade,
s.shot_id,
isn.version;
mentioned query gives 'Fresh' value in all field in (submit_type) column. which is not correct.
What I need exactly is, I am grouping column and finding MIN(value) of column,
Work Flow: -
grade A => group (shot_name) => min(version_submited) => set 'Fresh' else 'Once submitted' in (submit_type)
In Grade 'A' have same shot_name, grouping this (shot_name) and then finding min(version_submited) if min value found then set 'fresh' else set 'once submitted' value in (submit_type) column.
Also for Grade B like Grade A.
I need result like this =>
+----+-------+-----------------------------+-------------------------+-------------------+----------------+
| Id | grade | shot_name | submitted_by_supervisor | version_submitted | submit_type |
+----+-------+-----------------------------+-------------------------+-------------------+----------------+
| 27 | A | elx_reel01_scn1020_shot1720 | Salil Devji | 33 | Fresh |
| 27 | A | elx_reel01_scn1020_shot1720 | Deepali | 34 | Once Submitted |
| 37 | A | elx_reel01_scn1030_shot3480 | Salil Devji | 15 | Fresh |
| 37 | A | elx_reel01_scn1030_shot3480 | Salil Devji | 20 | Once Submitted |
| 7 | B | elx_reel01_scn1010_shot1030 | Darshan | 4 | Fresh |
| 7 | B | elx_reel01_scn1010_shot1030 | Varion | 6 | Once Submitted |
| 17 | B | elx_reel01_scn1010_shot1140 | Varion | 17 | Once Submitted |
| 17 | B | elx_reel01_scn1010_shot1140 | Varion | 14 | Fresh |
+----+-------+-----------------------------+-------------------------+-------------------+----------------+
The issue here is that you are grouping by on isn.version field as well, and trying to compute the minimum of the same field in that group. It will simply return the same value, and that is why all are coming as "Fresh". You will need to determine the minimum isn.version value for a group of (grade, shot_id) separately in a subquery (Derived Table), and then use that to check whether minimum or not.
SELECT s.shot_id,
s.shot_name ,
isn.reviewer AS submitted_by_supervisor,
isn.version AS version_submitted,
isn.grade AS grade,
CASE
WHEN isn.version = dt.min_version THEN 'FRESH'
ELSE 'Once Submitted'
END AS 'submit_type'
FROM viewd_elx.india_supe_note isn
JOIN viewd_elx.shot s
ON s.shot_id = isn.shot_id
JOIN viewd_elx.team t
ON isn.shot_id = t.shot_id
JOIN viewd_elx.viewd_team vt
ON isn.shot_id = vt.shot_id
JOIN (
SELECT grade,
shot_id,
MIN(version) AS min_version
FROM viewd_elx.india_supe_note
WHERE promoted = 'YES'
AND grade IN ('A', 'B')
GROUP BY grade,
shot_id
) AS dt
ON dt.grade = isn.grade
AND dt.shot_id = isn.shot_id
WHERE isn.promoted='Yes'
AND isn.grade IN ('A','B')
GROUP BY s.shot_id,
s.shot_name,
isn.reviewer,
isn.version,
isn.grade,
dt.min_version

MySQL retrieve last record in JOIN with group by

I have following tables with data as:
1.Table follow_up as :
mysql> select * from follow_up;
+--------------+----------------+--------------------------------------------------+-------------------+---------+---------------+-----------+---------------+----------+
| follow_up_id | feedback_close | feedback_open | is_email_required | is_Open | reminder_date | client_id | conclusion_id | stage_id |
+--------------+----------------+--------------------------------------------------+-------------------+---------+---------------+-----------+---------------+----------+
| 1 | NULL | dsffsdfsdfsd | 1 | 1 | 2017-09-20 | 101 | 96 | 72 |
| 2 | NULL | FSGDFHFGHFG | 1 | 1 | 2017-09-28 | 101 | 251 | 72 |
| 3 | NULL | Tender stage fb | 0 | 1 | NULL | 101 | 98 | 163 |
| 4 | NULL | Call back tender stage update date from 28 to 30 | 1 | 1 | 2017-09-28 | 101 | 96 | 163 |
| 5 | NULL | Metting follow up for next meeting | 1 | 1 | 2017-10-02 | 101 | 96 | 73 |
+--------------+----------------+--------------------------------------------------+-------------------+---------+---------------+-----------+---------------+----------+
2. Table logs as :
mysql> SELECT * from logs where transaction = 'FLWUP';
+---------+---------+---------------------+---------+-------------+
| user_id | menu_id | logs_time | tran_id | transaction |
+---------+---------+---------------------+---------+-------------+
| 84 | 69 | 2017-09-19 19:31:04 | 1 | FLWUP |
| 84 | 69 | 2017-09-19 19:31:25 | 2 | FLWUP |
| 84 | 69 | 2017-09-20 19:10:41 | 2 | FLWUP |
| 84 | 69 | 2017-09-21 12:35:01 | 3 | FLWUP |
| 84 | 69 | 2017-09-21 12:35:26 | 4 | FLWUP |
| 84 | 69 | 2017-09-21 12:36:16 | 4 | FLWUP |
| 84 | 69 | 2017-09-21 12:38:30 | 5 | FLWUP |
+---------+---------+---------------------+---------+-------------+
7 rows in set (0.00 sec)
3. table allcode as :
mysql> select * from allcode where code_type like 'MARK%';
+------------------+---------+------+----------------------+
| code_type | code_id | srno | code_name |
+------------------+---------+------+----------------------+
| MARKETING_STAGES | 72 | 1 | Enquiry |
| MARKETING_STAGES | 73 | 3 | Meeting |
| MARKETING_STAGES | 74 | 4 | Presentation |
| MARKETING_STAGES | 163 | 2 | Tender |
+------------------+---------+------+----------------------+
11 rows in set (0.00 sec)
I have invoked a query and got result as :
mysql> select f.follow_up_id,f.feedback_open, f.feedback_close, f.reminder_date,
ast.code_name as stage, ac.code_name as conclusion, max(l.logs_time)
from follow_up f
join logs l on l.tran_id = f.follow_up_id
join allcode ast on ast.code_id = f.stage_id
join allcode ac on ac.code_id = f.conclusion_id
where l.transaction='FLWUP' and f.client_id = 101
group by ast.code_name order by ast.srno;
+--------------+------------------------------------+----------------+---------------+---------+------------+---------------------+
| follow_up_id | feedback_open | feedback_close | reminder_date | stage | conclusion | max(l.logs_time) |
+--------------+------------------------------------+----------------+---------------+---------+------------+---------------------+
| 1 | dsffsdfsdfsd | NULL | 2017-09-20 | Enquiry | Call Back | 2017-09-20 19:10:41 |
| 3 | Tender stage fb | NULL | NULL | Tender | Next | 2017-09-21 12:36:16 |
| 5 | Metting follow up for next meeting | NULL | 2017-10-02 | Meeting | Call Back | 2017-09-21 12:38:30 |
+--------------+------------------------------------+----------------+---------------+---------+------------+---------------------+
3 rows in set (0.00 sec)
But I want result as :
+--------------+-----------------------------------------------------+----------------+---------------+---------+------------+---------------------+
| follow_up_id | feedback_open | feedback_close | reminder_date | stage | conclusion | max(l.logs_time) |
+--------------+-----------------------------------------------------+----------------+---------------+---------+------------+---------------------+
| 2 | FSGDFHFGHFG | NULL | 2017-09-20 | Enquiry | Call Back | 2017-09-20 19:10:41 |
| 4 | Call back tender stage update date from 28 to 30 | NULL | NULL | Tender | Next | 2017-09-21 12:36:16 |
| 5 | Metting follow up for next meeting | NULL | 2017-10-02 | Meeting | Call Back | 2017-09-21 12:38:30 |
+--------------+-----------------------------------------------------+----------------+---------------+---------+------------+---------------------+
3 rows in set (0.00 sec)
I'm not able to JOIN and group by to get required result.
column conclusion_id and stage_id of table follow_up are referring to code_id of table allcode.
Question :
the result I want is to be
group by stage_id,
order by srno of allcode and
last/recent follow_up_id of follow_up table
DEMO Includes my answer, original question with full group by needed, and Reupal's answer in demo. You were missing the values in your sample data for conclusionID so I just created them based on ID (now updated to ISO, Callback but missing 98.)
and my results don't match yours in this column; but I believe your expected results are in error.
Seems like you want the max follow_up_ID for each stage_ID when multiple stage_ID's exist
This can be handled by a derived table/inline view getting that max follow_UP_ID grouped by the stage_ID and a joining it back to your set. to limit results to include only the max follow_Up_ID by stage_Id.
I'm also not a fan of mySQL's extended group by and prefer including all columns not aggregated in the select in the group by. Using the extended group by tends to hide potential problems. In this case grouping by just the ast.code_name allowed the engine to select a non distinct value from the other columns. You ended up not getting the desired results and furthermore it hide the fact you would get multiple records in your query were it not for the extended group by use/misuse.
SELECT f.follow_up_id,f.feedback_open, f.feedback_close, f.reminder_date,
ast.code_name as stage, ac.code_name as conclusion, max(l.logs_time)
from follow_up f
join logs l on l.tran_id = f.follow_up_id
join allcode ast on ast.code_id = f.stage_id
join allcode ac on ac.code_id = f.conclusion_id
JOIN SELECT max(follow_up_ID) MFID, stage_ID
FROM follow_up
GROUP BY stage_ID) Z
on f.follow_up_ID = Z.MFID
and F.Stage_ID = Z.Stage_ID
WHERE l.transaction='FLWUP' and f.client_id = 101
GROUP BY f.follow_up_id,f.feedback_open, f.feedback_close, f.reminder_date,
ast.code_name , ac.code_name
ORDER BY ast.srno;
Try below, notice ordering and group by sequence.
select f.follow_up_id,f.feedback_open, f.feedback_close, f.reminder_date,
ast.code_name as stage, ac.code_name as conclusion, max(l.logs_time)
from follow_up f
join logs l on l.tran_id = f.follow_up_id
join allcode ast on ast.code_id = f.stage_id
join allcode ac on ac.code_id = f.conclusion_id
where l.transaction='FLWUP' and f.client_id = 101
group by follow_up.stage_id order by ast.srno, follow_up.follow_up_id DESC;
This should works, and if its not then you should search like how to set ordering on multiple column.
Ref. article- SQL multiple column ordering

MySQL Join Query without duplicate values

invoice table
SELECT id, fname, gtotal, `date` FROM invoice WHERE id = 1;
| id | fname | gtotal | date |
|----|---------|--------|-----------------------|
| 1 | Brandon | 860 | May, 11 2016 00:00:00 |
invoice_contents table,
SELECT * FROM invoice_contents WHERE invoice_id = 1;
| id | invoice_id | item | price | quantity | discount | total |
|----|------------|------------|-------|----------|----------|-------|
| 1 | 1 | Dextrose | 10 | 10 | 5 | 95 |
| 2 | 1 | Nescaine | 20 | 30 | 10 | 540 |
| 3 | 1 | Anticavity | 30 | 10 | 25 | 225 |
This JOIN query
SELECT invoice.id, invoice.fname, invoice_contents.item,
invoice_contents.price, invoice_contents.quantit,
invoice_contents.discount, invoice_contents.total,
invoice.gtotal
FROM invoice_contents
INNER JOIN invoice ON invoice_contents.invoice_id=1 AND invoice.id=1;
gives this result.
| id | fname | item | price | quantity | discount | total | gtotal |
|----|---------|------------|-------|----------|----------|-------|--------|
| 1 | Brandon | Dextrose | 10 | 10 | 5 | 95 | 860 |
| 1 | Brandon | Nescaine | 20 | 30 | 10 | 540 | 860 |
| 1 | Brandon | Anticavity | 30 | 10 | 25 | 225 | 860 |
I need this result.
| id | fname | item | price | quantity | discount | total | gtotal |
|----|---------|------------|-------|----------|----------|-------|--------|
| 1 | Brandon | Dextrose | 10 | 10 | 5 | 95 | 860 |
| | | Nescaine | 20 | 30 | 10 | 540 | |
| | | Anticavity | 30 | 10 | 25 | 225 | |
I am just a beginner in MySQL. I have been trying from this morning to get this kind of output by experimenting on different combinations please help me out.
#Rex, Your select is correct. You should make desired output using some script e.g. PHP.
try this in SQL:
in this Query i save everytime fname in a variable is not equal and at the next row i compare it and return a empty string is it equal. and the same for gtotal.
the cross join is only to initialize the variables.
in this case it is important that the rows are order by fname to ensure that the same name is behind each other
SELECT
invoice.id,
IF(#last_fname = invoice.fname, '', (#last_fname:=invoice.fname)) as fname,
invoice_contents.item,
invoice_contents.price,
invoice_contents.quantity,
invoice_contents.discount,
IF(#last_gtotal = invoice.gtotal, '', (#last_gtotal:=invoice.gtotal)) as gtotal
FROM invoice_contents
INNER JOIN invoice ON invoice_contents.invoice_id=1 AND invoice.id=1
CROSS JOIN ( select #last_fname := '' , #last_gtotal := '' ) AS parameter
ORDER BY invoice.fname;
Sample
MariaDB [bb]> SELECT
-> invoice.id,
-> IF(#last_fname = invoice.fname, '', (#last_fname:=invoice.fname)) AS fname,
-> invoice_contents.item,
-> invoice_contents.price,
-> invoice_contents.quantity,
-> invoice_contents.discount,
-> IF(#last_gtotal = invoice.gtotal, '', (#last_gtotal:=invoice.gtotal)) AS gtotal
-> FROM invoice_contents
-> INNER JOIN invoice ON invoice_contents.invoice_id=1 AND invoice.id=1
-> CROSS JOIN ( SELECT #last_fname:='' , #last_gtotal:='' ) AS parameter
-> ORDER BY invoice.fname;
+----+---------+------------+-------+----------+----------+--------+
| id | fname | item | price | quantity | discount | gtotal |
+----+---------+------------+-------+----------+----------+--------+
| 1 | Brandon | Dextrose | 10.00 | 10 | 5.00 | 860.00 |
| 1 | | Nescaine | 20.00 | 30 | 10.00 | |
| 1 | | Anticavity | 30.00 | 10 | 25.00 | |
+----+---------+------------+-------+----------+----------+--------+
3 rows in set, 1 warning (0.00 sec)
MariaDB [bb]>

sql select query from two different tables WHERE active=1

i try select all columns from two different tables WHERE active = 1
i have 2 tables table_pro and table_basic,
sql:"select * from table_basic,table.name";
and 2 condition:
WHERE active = 1
WHERE table_pro.id = table_basic.name.id
how to make it correctly
Here is table_pro
+----+--------+---------+-----------+
| id | people | rooms | active |
+----+--------+---------+-----------+
| 1 | 5 | 10 | 0 |
| 2 | 12 | 17 | 0 |
| 3 | 21 | 38 | 1 |
+----+--------+---------+-----------+
Here is table_basic
+---------+-------+---------+------------+----------+
| name_id | name | balance | title | time |
+---------+-------+---------+------------+----------+
| 1 |shop | 100 | failed | 15:10:20 |
| 2 |factory| 75 | error | 15:10:20 |
| 3 |studio | 25 | timed_out | 15:10:20 |
+---------+-------+---------+------------+----------+
I'd like to have this output result only rows (from of all columns) with status active = 1
+-----+-------+----- --+--------+-------+----------+---------+--------+
| id | people| rooms | name |balance| title | time | active |
+-----+-------+--------+--------+-------+----------+---------+--------+
| 3 | 21 | 38 | studio |25 | timed_out| 15:10:20| 1 |
+-----+-------+--------+--------+-------+----------+---------+--------+
Thanks
SELECT A.id, A.people, A.rooms, B.name, B.balance, B.title, B.time, A.active
FROM
table_pro AS A
JOIN
table_basic AS B
ON
A.id = B.name_id
WHERE
A.id = 3
SELECT table_pro.*, table_basic.*
FROM table_pro
INNER JOIN table_basic
ON table_basic.name_id = table_pro.id
WHERE table_pro.active = 1

Get available stocks to sell

What I have until now: http://sqlfiddle.com/#!2/bbfec/6
I want to get the quanity of shares for a given stock, that a given company has available to sell - grouped by price. For example, for company number 9 and stock number 1, I want the data like this:
| id | name | price | date | quantity | total |
------------------------------------------------------------------
| 3 | ALTR | 2.240 | 2015-05-12 04:29:29 | 50 | 112.00 |
| 7 | ALTR | 2.449 | 2014-06-10 18:21:02 | 50 | 122.45 |
Because company 9 bought 200 stocks on 2015-05-12 04:29:29, sold 100 on 2014-06-10 15:50:17, more 50 on 2014-06-10 17:06:18 and bought 50 on 2014-06-10 18:21:02.
I don't want the total of all shares, because they have different prices when a company acquires them. The price and the date are the purchasing price and date but the quantity is what is left from a certain purchasing.
Thanks in advance.
Strawberry, the desired result:
| id | price | date | quantity |
-----------------------------------------------
| 3 | 2.240 | 12-05-2015 | 50 |
| 7 | 2.449 | 10-06-2014 | 50 |
Start with:
select id_acao, id_empresa, ifnull(bought,0) - ifnull(sold,0) as stock
from
(
select id_acao, id_empresa,
(select sum(quantidade) from acao_trans where tipo='C' and id_acao=a.id_acao and id_empresa=a.id_empresa) as bought,
(select sum(quantidade) from acao_trans where tipo='V' and id_acao=a.id_acao and id_empresa=a.id_empresa) as sold
from acao_trans a group by id_acao,id_empresa
) x
;
+---------+------------+-------+
| id_acao | id_empresa | stock |
+---------+------------+-------+
| 1 | 4 | 1500 |
| 1 | 9 | 100 |
| 8 | 9 | 3500 |
| 13 | 9 | 5000 |
+---------+------------+-------+
And join this query to your base acao and empresa tables.
Remark: For statistics etc. it would be easier to use negative quantities for selling transactions instead of a transaction type 'C' and 'V'.
For ease of (my) comprehension, I translated and adjusted your stock table slightly...
SELECT a.stock_id
, a.company_id
, a.transaction_date
, a.price
, COALESCE(a.quantity - SUM(b.quantity),a.quantity) quantity
, COALESCE(a.quantity - SUM(b.quantity),a.quantity) * a.price subtotal
FROM stock_company a
LEFT
JOIN
( SELECT x.stock_id
, x.company_id
, MAX(x.transaction_date) min_transaction_date
, y.quantity
FROM stock_company x
JOIN stock_company y
ON y.stock_id = x.stock_id
AND y.company_id = x.company_id
AND y.transaction_date <= x.transaction_date
AND y.transaction_type <> x.transaction_type
WHERE y.transaction_type = 'SELL'
GROUP
BY x.stock_id
, x.company_id
, y.quantity
) b
ON b.stock_id = a.stock_id
AND b.company_id = a.company_id
AND b.min_transaction_date = a.transaction_date
WHERE a.stock_id = 1
AND a.company_id = 9
AND a.transaction_type = 'BUY'
GROUP
BY stock_id
, company_id
, transaction_date;
+----------+------------+---------------------+-------+----------+----------+
| stock_id | company_id | transaction_date | price | quantity | subtotal |
+----------+------------+---------------------+-------+----------+----------+
| 1 | 9 | 2014-06-10 18:21:02 | 2.449 | 50 | 122.450 |
| 1 | 9 | 2015-05-12 04:29:29 | 2.240 | 50 | 112.000 |
+----------+------------+---------------------+-------+----------+----------+
http://www.sqlfiddle.com/#!2/cfa4d/1
Note that this hasn't been tested extensively so there may be a flaw (or perhaps several flaws!) in my logic, but it seems to work well enough on the data set provided.
EDIT: I made a slight adjustment - still not sure if it's enough. Let me know.
Maybe now I've understood it. How about this:
select c.id,c.id_empresa,c.id_acao,c.data as c_data,c.quantidade as c_quantidade,v.preco,v.id as v_id,v.data as v_data,ifnull(v.quantidade,0) as v_quantidade, c.preco*v.quantidade as bought, v.preco*v.quantidade as sold
from acao_trans c
left join acao_trans v
on c.id=v.parent
order by id_empresa, id_acao,c_data,v_data
which results in
+----+------------+---------+---------------------+--------------+-------+------+---------------------+--------------+----------+----------+
| id | id_empresa | id_acao | c_data | c_quantidade | preco | v_id | v_data | v_quantidade | bought | sold |
+----+------------+---------+---------------------+--------------+-------+------+---------------------+--------------+----------+----------+
| 4 | 4 | 1 | 2014-06-10 08:59:09 | 2000 | 2.385 | 8 | 2014-06-11 10:39:48 | 500 | 1184.000 | 1192.500 |
| 8 | 4 | 1 | 2014-06-11 10:39:48 | 500 | NULL | NULL | NULL | 0 | NULL | NULL |
| 5 | 9 | 1 | 2014-06-10 15:50:17 | 100 | NULL | NULL | NULL | 0 | NULL | NULL |
| 6 | 9 | 1 | 2014-06-10 17:06:18 | 50 | NULL | NULL | NULL | 0 | NULL | NULL |
| 7 | 9 | 1 | 2014-06-10 18:21:02 | 50 | NULL | NULL | NULL | 0 | NULL | NULL |
| 3 | 9 | 1 | 2015-05-12 04:29:29 | 200 | 2.430 | 5 | 2014-06-10 15:50:17 | 100 | 224.000 | 243.000 |
| 3 | 9 | 1 | 2015-05-12 04:29:29 | 200 | 2.449 | 6 | 2014-06-10 17:06:18 | 50 | 112.000 | 122.450 |
| 2 | 9 | 8 | 2015-05-12 04:27:56 | 3500 | NULL | NULL | NULL | 0 | NULL | NULL |
| 1 | 9 | 13 | 2015-05-12 04:25:52 | 5000 | NULL | NULL | NULL | 0 | NULL | NULL |
+----+------------+---------+---------------------+--------------+-------+------+---------------------+--------------+----------+----------+
Can you go on from there?
Ok, now I think I got it.
Here's the query resulting what I wanted:
SELECT p.id
, a.nome
, p.preco
, date_format(p.`data`,'%m/%d/%Y') AS `data`
, COALESCE(p.quantidade-SUM(f.quantidade), p.quantidade) AS quantidade
, p.preco*COALESCE(p.quantidade-SUM(f.quantidade), p.quantidade) AS total
FROM acao_trans p
LEFT JOIN acao_trans f
ON p.id=f.parent
INNER JOIN acao a
ON p.id_acao=a.id
WHERE p.parent IS NULL
AND p.id_acao=1
AND p.id_empresa=9
GROUP BY p.id
Fiddle: http://sqlfiddle.com/#!2/bbfec/64.
What I did: I joined the table that matters (acao_trans "p") with itself ("f") and I used Sum function to aggregate all the quantities of second argument, giving me the total of all sold shares. If there are records on "f" I want to subtract that total of the quantity of purchasing shares ("p"). If there is not a correspondence it will show null fields and I show purchased quantity. After it's done it's kind of simple. Quantity was what really mattered here, with that I was able to reach other things easily.