Join error in using CTE in Hive - mysql

i have two queries which are doing almost the similar work.
One does it without CTEs and one with CTEs. I am unable to figure out why the second query is giving absolutely no results while the first one is.
I have spent the last two hours trying to figure this out by trying out various joins and the same joins working in query 1 are not working in query 2. I hope someone can guide me with this.
First query (Returns results):
WITH MessageCTE AS
(
SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02 as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
SELECT COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency ELSE NULL END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.5) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.8) AS 80Percentile
, PERCENTILE(latency, 0.9) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
(
SELECT a.dt, a.to_user, (latency_dl.ts - latency_pb.ts) as latency
FROM
(
SELECT dt
, id, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'pb'
) as latency_pb
INNER JOIN
(SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'rdl'
AND family = 'stm'
) as latency_rdl
ON latency_pb.dt = latency_rdl.dt and latency_pb.to_user = latency_rdl.to_user and latency_pb.id = latency_rdl.id
INNER JOIN
(
SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'dl'
) as latency_dl
ON latency_rdl.dt = latency_dl.dt and latency_rdl.to_user = latency_dl.to_user and latency_rdl.id = latency_dl.id) AS UserLatency;
First Query Output:
Now Second Query, is a slight modification and all the same conditions, but for some reason it is returning no matches. Hopefully someone can guide me out, i just spent around 2 hours trying some joins out and i am unable to figure out why they are not happening.
Second Query:
WITH MessageCTE_pb AS
(
SELECT dt, id, ts, to_user
FROM
(
SELECT dt, id, min(ts) as ts, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'pb'
GROUP BY dt, to_user, id
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
, MessageCTE_dl AS
(
SELECT dt, id, ts, to_use
FROM
(
SELECT dt, id, max(ts) as ts, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'dl'
GROUP BY dt, to_user, id
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
, MessageCTE_rdl AS
(
SELECT dt, id, to_user
FROM
(
SELECT DISTINCT dt, id, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'rdl'
AND family = 'stm'
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
SELECT COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency ELSE NULL END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.5) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.8) AS 80Percentile
, PERCENTILE(latency, 0.9) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
(
SELECT a.dt, a.to_user, (latency_dl.ts - latency_pb.ts) as latency
FROM MessageCTE_pb as latency_pb
INNER JOIN MessageCTE_rdl as latency_rdl
ON latency_pb.dt = latency_rdl.dt and latency_pb.to_user = latency_rdl.to_user and latency_pb.id = latency_rdl.id
INNER JOIN MessageCTE_dl as latency_dl
ON latency_rdl.dt = latency_dl.dt and latency_rdl.to_user = latency_dl.to_user and latency_rdl.id = latency_dl.id) AS UserLatency;
Thanks!
Second Query Result:

Another comment in an answer block so I can post a bunch of SQL...
What is the result of this?
WITH
UserLatency AS
(
SELECT
latencydata.dt,
latencydata.to_user,
latencydata.id,
MAX(CASE WHEN latencydata.class = 'dl' THEN latencydata.ts END)
-
MIN(CASE WHEN latencydata.class = 'pb' THEN latencydata.ts END)
AS latency
FROM
dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02 AS latencydata
INNER JOIN
dhruv.UsersOn503AndAbove_20171201_200k AS required_users
ON latencydata.to_user = required_users.user_id
GROUP BY
latencydata.dt,
latencydata.to_user,
latencydata.id
HAVING
0 < SUM(CASE WHEN latencydata.class = 'rdl'
AND latencydata.family = 'stm' THEN 1 END)
)
SELECT
COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.50) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.80) AS 80Percentile
, PERCENTILE(latency, 0.90) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
UserLatency
;

Related

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.

sql query with DISTINCT make huge performance issue

i have a query to get summary of donations
SELECT CONVERT(CHAR(2), CAST(pb.PayrollDate AS DATETIME), 101)
+ '/' + CONVERT(CHAR(4), CAST(pb.PayrollDate AS DATETIME), 120) AS Closing_Month ,
CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112) AS Closing_Year ,
COUNT(DISTINCT Donation.Employee) + ( SELECT COUNT(*)
FROM dbo.Donation
INNER JOIN PayrollBatch pbd ON Donation.PayrollBatch = pbd.ID
WHERE CONVERT(CHAR(6), CAST(pbd.PayrollDate AS DATETIME), 112) = CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112)
AND DonationType = 5
)AS 'Donors' ,
COUNT (DISTINCT( CASE WHEN Donation.DonationType = 1 OR Donation.DonationType = 5 THEN CharityDetails.ID
END ))AS 'Charities',
( CAST(COUNT(DISTINCT Donation.Employee) AS DECIMAL(18, 2))
/ ( SELECT SUM(NumberOfEmployees)
FROM OrganisationDetail
WHERE ID = Donation.OrganisationDetail
AND IsDeleted = 0
) ) * 100 AS 'Participation_Rate' ,
SUM(CASE WHEN Donation.DonationType = 1 OR Donation.DonationType = 5 THEN Donation.Amount
ELSE 0
END) AS 'Employee_Donations' ,
SUM(CASE WHEN Donation.DonationType = 2 THEN Donation.Amount
ELSE 0
END) AS 'Matched_Donations' ,
SUM(CASE WHEN Donation.DonationType = 1
OR Donation.DonationType = 2 OR Donation.DonationType = 5 THEN Donation.Amount
ELSE 0
END) AS 'Total_Donations'
FROM Donation
INNER JOIN OrganisationDetail AS OrganisationDetail_1 ON Donation.OrganisationDetail = OrganisationDetail_1.ID
INNER JOIN CharityProjectDetails ON Donation.CharityProjectDetails = CharityProjectDetails.ID
INNER JOIN CharityDetails ON CharityProjectDetails.CharityDetails = CharityDetails.ID
INNER JOIN PayrollBatch pb ON Donation.PayrollBatch = pb.ID
LEFT JOIN Employee ON Donation.Employee = Employee.ID
LEFT JOIN DonationIntent ON Donation.DonationIntent = DonationIntent.ID
LEFT JOIN EmployeeAddress ON Employee.ID = EmployeeAddress.Employee
LEFT JOIN dbo.PayrollBatchOther pbo ON pbo.PayrollBatch = pb.ID
GROUP BY CONVERT(CHAR(2), CAST(pb.PayrollDate AS DATETIME), 101)
+ '/' + CONVERT(CHAR(4), CAST(pb.PayrollDate AS DATETIME), 120) ,
CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112) ,
Donation.OrganisationDetail
ORDER BY Closing_Year;
i need to get unique donors count from result set COUNT(DISTINCT e.ID) but with distinct query takes 7-9 sec to complete execution but without that it took only 1 sec how to improve that performance
Update
Here is the Paste The Plan

Combining Two SQL Select Queries with Where Clauses

I have two Oracle queries that I need combined through an inner join where the tables are joined using the person_uid field. This is because I need to compare what an employee's pay, job title, and supervisor was from one year to the next. I need to have the 2015 data and the 2014 data in the same row for each employee, so if this can be done by doing a subquery using an inner join on the person_uid field, that is the method that I believe will accomplish this.
Here is the first query that pulls the necessary 2015 data:
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE posn.position_contract_type = 'P'
AND posn.position_status <> 'T'
AND posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
AND p2.position = posn.position
AND p2.job_suffix = posn.job_suffix
AND p2.effective_date <= '01-Nov-2015')
order by person_uid
I need it to be joined to this query on the person_uid field so that each unique ID for the employee has the records for both years in a single row:
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE posn.position_contract_type = 'P'
AND posn.position_status <> 'T'
AND posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
AND p2.position = posn.position
AND p2.job_suffix = posn.job_suffix
AND p2.effective_date <= '01-Nov-2014')
order by person_uid
An easy way would be to use OR:
WHERE posn.position_contract_type = 'P' AND
posn.position_status <> 'T' AND
(posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
p2.position = posn.position AND
p2.job_suffix = posn.job_suffix AND
p2.effective_date <= '01-Nov-2014'
) OR
posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
p2.position = posn.position AND
p2.job_suffix = posn.job_suffix AND
p2.effective_date <= '01-Nov-2015'
)
)
In Oracle you could do a UNION or a UNION ALL.
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE ...
...
...
UNION ALL
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE ....
....
....;

how to calculate from each row value in sql

I have a table named general_ledger from which I need to show dr_amount, cr_amount and the balance between them as running_balance. That's why I have written a query that is given below. But I am getting the result of each query like the balance only of current row. But I need to produce the result with the remaining balance. Suppose First row dr_balance is 20000 and cr_balance is 5000 and remaining balance is 15000. In second row only cr_balance is 5000. Now the result should be 10000 with the deduction but my result is -5000. I have no idea how to fix this. Can anyone please help me on this? I need your help very much. Here is my query given below :
SELECT '' AS cost_center_id
, '' AS cost_center_name
, '' AS office_code
, CONVERT('2013-02-01',DATETIME) AS transaction_date
, '' AS accounts_head_id
, '' AS account_name
, '' AS opposite_accounts_head_id
, '' AS opposite_account_name
, 'Opening Balance' AS particulars
, tempOpeningBalance.dr_amount
, tempOpeningBalance.cr_amount
, '' AS voucher_no
, '' AS vin
FROM (SELECT IFNULL(mcoa.account_code,'1101010101100321') AS account_code
, IFNULL(mcoa.account_name,'Cash') AS account_name
, IFNULL(mcoa.account_type,'ASSET') AS accountType
, CAST(IFNULL(SUM(IFNULL(maingl.dr_balance,0)),0) AS DECIMAL(27,5)) AS dr_amount
, CAST(IFNULL(SUM(IFNULL(maingl.cr_balance,0)),0) AS DECIMAL(27,5)) AS cr_amount
FROM master_chart_of_accounts AS mcoa
INNER JOIN chart_of_accounts AS coa ON (mcoa.id = coa.master_chart_of_accounts_id AND mcoa.id = 80)
LEFT JOIN general_ledger AS maingl ON (coa.id = maingl.accounts_head_id AND coa.account_code='1101010101100321')
INNER JOIN
( SELECT gl.accounts_head_id, MAX(gl.gl_id) AS max_gl_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
FROM general_ledger AS gl
-- INNER JOIN voucher_info AS vi ON (gl.voucher_info_id = vi.id)
-- WHERE vi.posting_date < '2013-02-01' AND
WHERE gl.transaction_date < '2013-02-01' AND
gl.cost_center_id IN ('BI0000000000000000000001') AND
gl.country_id IN (1) AND
gl.office_code IN ('UG500013') AND
1=1
GROUP BY gl.accounts_head_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
ORDER BY gl.accounts_head_id
) AS tmpgl
ON ( maingl.office_code = tmpgl.office_code
AND maingl.office_type = tmpgl.office_type
AND maingl.accounts_head_id = tmpgl.accounts_head_id
AND maingl.country_id = tmpgl.country_id
AND maingl.cost_center_id = tmpgl.cost_center_id
AND maingl.gl_id = tmpgl.max_gl_id
)
WHERE mcoa.account_status_id = 1 AND
coa.account_status_id = 1
) AS tempOpeningBalance
UNION
SELECT vi.cost_center_id
, cc.center_name AS cost_center_name
, gl.office_code
, vi.posting_date AS transaction_date
, vd.accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.accounts_head_id) AS account_name
, vd.opposite_accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.opposite_accounts_head_id) AS opposite_account_name
, vd.particulars
, gl.dr_amount AS dr_amount -- here to check
, gl.cr_amount AS cr_amount
, vi.voucher_no
, vi.vin
FROM general_ledger AS gl
INNER JOIN voucher_info AS vi
ON (gl.voucher_info_id = vi.id)
INNER JOIN cost_center AS cc
ON (vi.cost_center_id = cc.id)
INNER JOIN voucher_details AS vd
ON (vi.id = vd.voucher_info_id)
INNER JOIN chart_of_accounts AS coa
ON (vd.accounts_head_id = coa.id)
WHERE vi.posting_date BETWEEN '2013-02-01' AND'2013-02-28'
AND vi.voucher_status_id = 3
AND vd.status_id = 1
AND vi.office_code = 'UG500063'
AND coa.account_code='1101010101100321'
AND coa.cost_center_id = 'BI0000000000000000000001'
ORDER BY cost_center_name
, office_code
, transaction_date;
Use a variable like this
SET #running_balance=0;
SELECT dr_amount AS dr_amount
, cr_amount AS cr_amount
, #running_balance := (#running_balance + dr_amount - cr_amount)
FROM general_ledger

MYSQL Select Query with UNION to mege data from three tables which shares the same FKey

my query is built like this, but I am not getting the expected result. I have tables like
company_group- group_company_id, group_company_name
store - store_id,store_name
sales_report- sales_id, group_company_id,store_id, sales_4,vat_4
warehouse_sales - warehouse_sales_id, warehouse_sales_id(FK-group_company_id), store_name(FK-store_id),date, sales_four_percent
Stock_recpt- Stock_recpt_id, group_company_id, receipt_date,input_vat_4
This the query to get the result like
company_group store_name Month sales_4 vat_4 input_vat
SELECT firm, store_name, MONTH, sales_4, vat_4, input_vat_4
FROM (select `company_group`.`group_company_name`as firm,`store`.`store_name`as store_name, MONTHNAME( receipt_date ) AS MONTH,0 AS sales_4, 0 as vat_4,sum(`input_vat_4_percent`)as input_vat_4 from
company_group,store, Stock_recpt
WHERE `company_group`.`group_company_id` = `Stock_recpt`.`group_company_id`and `store`.`store_id` = `Stock_recpt`.`store_id` and `Stock_recpt`.`purchase_type` = 'purchase_4_percent'
UNION
SELECT `company_group`.`group_company_name`as firm , `store`.`store_name`as store_name , MONTHNAME(date) AS MONTH , sum( `warehouse_sales`.`sales_four_percent`)as sales_4, sum( `warehouse_sales`.`vat_four_percent` ) AS vat_4, 0 as input_vat_4
from company_group,store, warehouse_sales
WHERE `company_group`.`group_company_id` = `warehouse_sales`.`firm_name`and `store`.`store_id` = `warehouse_sales`.`store_name`
UNION
SELECT `company_group`.`group_company_name` as firm, `store`.`store_name`as store_name,MONTHNAME( sale_date ) AS MONTH, sum( `sales_report`.`sales_four_percent`)as sales_4, sum( `sales_report`.`vat_four_percent` ) AS vat_4,0 as input_vat_4
FROM company_group,store, sales_report
WHERE `company_group`.`group_company_id` = `sales_report`.`group_company_id`and `store`.`store_id` = `sales_report`.`store_id`)a
GROUP BY firm , store_name,`MONTH`