Combining Two SQL Select Queries with Where Clauses - mysql

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 ....
....
....;

Related

Is it possible to pull from multiple tables and then insert the result into another table in the same query with MySQL?

I'm querying multiple tables with UNION ALL and then using the alias to insert the result into another table. It's telling me that I have a syntax error right after the INSERT INTO line. The query looks correct to me and the error is pretty vague. Any help would be appreciated!
SELECT
uploads.campaign_name as 'Campaign Name'
, date as Date
, country as Country
, region as Region
, amount_spent as 'Amount Spent'
, impressions as Impressions
, clicks as Clicks
, cpc as CPC
, ctr as CTR
, cpm as CPM
, category as Category
, subcategory as Subcategory
, source as Source
FROM (SELECT
facebook.ad_name as campaign_name
, facebook.day as 'date'
, CASE WHEN facebook.account_name = 'PMD Beauty' THEN 'US'
WHEN facebook.account_name = 'PMD Beauty United Kingdom' THEN 'UK'
WHEN facebook.account_name = 'PMD Beauty Australia' THEN 'AU'
WHEN facebook.account_name = 'PMD Beauty Europe' THEN 'EU' END as country
, facebook.region as region
, facebook.amount_spent as amount_spent
, facebook.impressions as impressions
, facebook.clicks as clicks
, facebook.cpc as cpc
, facebook.ctr as ctr
, facebook.cpm as cpm
, 'Facebook' as source
FROM
facebook
UNION ALL
SELECT
tiktok.campaign_name as campaign_name
, tiktok.date as 'date'
, tiktok.location as country
, null as region
, tiktok.cost as amount_spent
, tiktok.impression as impressions
, tiktok.click as clicks
, tiktok.cpc as cpc
, tiktok.ctr as ctr
, tiktok.cpm as cpm
, 'Tiktok' as source
FROM
tiktok
UNION ALL
SELECT
pinterest.ad_name as campaign_name
, pinterest.date as 'date'
, trim(substring_index(pinterest.targeting_value, ':', 1)) as country
, trim(substring_index(pinterest.targeting_value, ':', -1)) as region
, pinterest.spend_in_account_currency as amount_spent
, pinterest.impressions as impressions
, pinterest.link_clicks as clicks
, pinterest.cpc as cpc
, pinterest.ctr as ctr
, pinterest.cpm as cpm
, 'Pinterest' as source
FROM
pinterest
UNION ALL
SELECT
steelhouse.campaign_group_name as campaign_name
, steelhouse.date as 'date'
, null as country
, null as region
, steelhouse.total_spend as amount_spent
, steelhouse.impressions as impressions
, null as clicks
, null as cpc
, null as ctr
, null as cpm
, 'SteelHouse' as source
FROM
steelhouse
UNION ALL
SELECT
criteo.campaign as campaign_name
, criteo.day as 'date'
, null as country
, null as region
, criteo.cost as amount_spent
, criteo.displays as impressions
, criteo.clicks as clicks
, criteo.cpc as cpc
, criteo.ctr as ctr
, criteo.cpm as cpm
, 'Criteo' as source
FROM
criteo
UNION ALL
SELECT
hivewyre.creative_name as campaign_name
, hivewyre.date as 'date'
, 'US' as country
, null as region
, hivewyre.spend as amount_spent
, hivewyre.imps as impressions
, hivewyre.clicks as clicks
, null as cpc
, null as ctr
, null as cpm
, 'Hivewyre' as source
FROM
hivewyre
UNION ALL
SELECT
generic_social_media.campaign_name as campaign_name
, generic_social_media.date as 'date'
, generic_social_media.country as country
, generic_social_media.region as region
, generic_social_media.amount_spent as amount_spent
, generic_social_media.impressions as impressions
, generic_social_media.clicks as clicks
, generic_social_media.cpc as cpc
, generic_social_media.ctr as ctr
, generic_social_media.cpm as cpm
, 'Generic Template' as source
FROM
generic_social_media) uploads
LEFT JOIN
product_to_category
ON uploads.campaign_name LIKE BINARY concat('%', product_to_category.product, '%')
WHERE uploads.date >= :startDate
INSERT INTO
marketing (campaign_name, category, subcategory, 'date', country, region, amount_spent, impressions, clicks, cpc, ctr, cpm, source, plenadata__created_at, plenadata__updated_at)
SELECT
campaign_name
, category
, subcategory
, 'date'
, country
, region
, amount_spent
, impressions
, clicks
, cpc
, ctr
, cpm
, source
, NOW()
, NOW()
FROM
uploads
In the terminal:
`error`='\t\t\t\tmarketing (campaign_name, category, subcategory, \'date\', country\' at line 149',`stack`='SequelizeDatabaseError: You have an error in your SQL syntax;

How to sort query results by date then specific column values in mysql

I'm trying to sort my query results by date, then within each timeframe by if the status is 'sold', then if the status is 'contingent', then if the status is 'canceled'. Nothing I do to the ORDER BY clause seems to work. I would really appreciate some insight into what I'm doing wrong. Here's my query as it is now:
SELECT
subdivision community
, lot_number lot
, homeowner buyer
, agent_initials agent
, date_sold date
, sales.plan plan
, sales.inv_pre type
, sold_price price
, 'sold' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_sold,'-',2),'-',-1) month
FROM
sales
JOIN
third_party_sources
ON sales.job_id = third_party_sources.job_id
WHERE
sales.is_contingent is null
AND sales.date_sold BETWEEN :startDate AND :endDate
OR sales.is_contingent = 0
AND sales.date_sold BETWEEN :startDate AND :endDate
UNION
SELECT
subdivision community
, lot_number lot
, homeowner buyer
, agent_initials agent
, date_sold date
, sales.plan plan
, sales.inv_pre type
, sold_price price
, 'contingent' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_sold,'-',2),'-',-1) month
FROM
sales
JOIN
third_party_sources
ON sales.job_id = third_party_sources.job_id
WHERE
sales.is_contingent
AND sales.date_sold BETWEEN :startDate AND :endDate
UNION
SELECT
subdivision community
, lot_number lot
, buyer_name buyer
, agent_initials agent
, date_canceled date
, null plan
, null type
, null price
, 'canceled' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_canceled,'-',2),'-',-1) month
FROM
cancellations
JOIN
third_party_sources
ON cancellations.job_id = third_party_sources.job_id
WHERE
cancellations.date_cancelled BETWEEN :startDate AND :endDate
ORDER BY
date
, status = 'sold'
, status = 'contingent'
, status = 'canceled'
I think you want:
ORDER BY date, FIELD(status, 'sold', 'contingent', 'canceled')
This assumes that these are the only three values. If there are more values, then your method would work . . . with DESC:
ORDER BY date, (status = 'sold') DESC, (status = 'contingent') DESC, (status = 'canceled') DESC

Join error in using CTE in Hive

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
;

MySQL - structure a query with different values that requires a lookup from the same table

This is my query:
SELECT f.pending
, f.title
, f.funeraltype
, f.firstname
, f.middlename
, f.lastname
, f.suffix
, f.displayage
, f.age
, f.displaycity
, f.city
, f.displaydate
, f.date
, f.aftersunset
, f.funeraldate
, f.displayfuneraldate
, f.ftime
, f.displayservicelocation
, l.location
, f.displaycemetery
, c.name
, f.displayobituary
, f.obituary
, f.displaycharity1
, ch.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.memorialbook
, f.displayshiva
, f.displaytime
, f.shivaendpart
, f.shivauntil
, f.shivaatresidence
, f.shivaname
, f.shivaaddress
, f.shivacity
, f.shivastate
, f.shivazip
, f.shivaphone
, f.shivacomment
, f.displayfamilymembers
, f.familymembers
, f.displayclergy
, f.clergy
, f.livevideo
, f.archivevideo
, f.video
, f.usemp4video
, f.mp4video
, f.custom_text
, f.charities_footnote
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
, locations l
, cemeteries c
, charities ch
WHERE f.servicelocation = l.locationid
AND f.cemetery = c.cemeteryID
AND f.charity1 = ch.CharityID
AND f.charity2 = ch.CharityID
AND f.charity3 = ch.CharityID
AND f.charity4 = ch.CharityID
AND f.charity5 = ch.CharityID
ch.name is what I'm looking to extract. f.charity1, f.charity2, f.charity3, f.charity4, & f.charity5 all contain different IDs that require a lookup in the 'charities' table. How would I structure this query to display each charity name?
SELECT f.pending
, l.location
, f.displaycemetery
, c.name
, f.displaycharity1
, ch.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
JOIN locations l
ON l.locationid = f.servicelocation
JOIN cemeteries c
ON c.cemeteryID = f.cemetery
JOIN charities ch1
ON ch1.CharityID = f.charity1
JOIN charities ch2
ON ch2.CharityID = f.charity2
etc.
try this:
SELECT
f.pending
, f.title
, f.funeraltype
, f.firstname
, f.middlename
, f.lastname
, f.suffix
, f.displayage
, f.age
, f.displaycity
, f.city
, f.displaydate
, f.date
, f.aftersunset
, f.funeraldate
, f.displayfuneraldate
, f.ftime
, f.displayservicelocation
, l.location
, f.displaycemetery
, c.name
, f.displayobituary
, f.obituary
, f.displaycharity1
, ch1.name
, ch2.name
, ch3.name
, ch4.name
, ch5.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.memorialbook
, f.displayshiva
, f.displaytime
, f.shivaendpart
, f.shivauntil
, f.shivaatresidence
, f.shivaname
, f.shivaaddress
, f.shivacity
, f.shivastate
, f.shivazip
, f.shivaphone
, f.shivacomment
, f.displayfamilymembers
, f.familymembers
, f.displayclergy
, f.clergy
, f.livevideo
, f.archivevideo
, f.video
, f.usemp4video
, f.mp4video
, f.custom_text
, f.charities_footnote
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
INNER JOIN locations l on f.servicelocation = l.locationid
INNER JOIN cemeteries c ON f.cemetery = c.cemeteryID
INNER JOIN charities ch1 ON f.charity1 = ch1.CharityID
INNER JOIN charities ch2 ON f.charity2 = ch2.CharityID
INNER JOIN charities ch3 ON f.charity3 = ch3.CharityID
INNER JOIN charities ch4 ON f.charity4 = ch4.CharityID
INNER JOIN charities ch5 ON f.charity5 = ch5.CharityID

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