MYSQL inner join 2 tables and sum() - mysql

I am unable to get sum() after joining 2 tables, one is HEADER AND DETAIL. It just gives only 0 result for the below sql statement. Need some help:
My tables:
INVHDR:
Invno, Invdate, Ac_code
100 2013-04-01 2
101 2013-04-30 2
INVDTLS:
Invno, Prod_desc, Amount
100 Argon 155
100 Argon 250
101 Oxygen 322
101 Oxygen 065
Desired result:
Sum of amts: 405
MYSQL statement to inner join and sum()
SELECT
a.Invno, a.Ac_code, a.Invdate, b.*
FROM INVHDR a
INNER JOIN (
SELECT
Invno, Prod_desc, SUM( Amount ) AS amts
FROM INVDTLS
WHERE Prod_desc='Argon'
) AS b ON a.Invno = b.Invno
WHERE
a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01'
AND '2013-04-30'
GROUP BY a.Ac_code

Why are you writing such a complicated Query, try this:
SELECT sum(b.Amount)
FROM INVHDR a
INNER JOIN INVDTLS b
ON a.Invno = b.Invno
WHERE a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30'
AND b.Prod_desc='Argon'
--Group by b.Prod_desc,a.Invno, a.Ac_code
Here is the SQL Fiddle

check http://www.sqlfiddle.com/#!2/86377/8 Thank you #Luv
SELECT
a.Invno, a.Ac_code, b.Prod_desc, SUM(b.Amount) AS Amount
FROM INVHDR a
INNER JOIN INVDTLS b ON a.Invno = b.Invno
WHERE
a.Ac_code = 2 -- a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30'
AND b.Prod_desc='Argon'
group by a.Invno, a.Ac_code, b.Prod_desc

Related

Issue getting while fetching data using joins

I have four table and structure as below :
1)Budget
id Budget_name
1 test1
2 test2
3 test3
2)Yearly Budget
id amount_yearly budgetid
1 1000 1
2 2000 2
3 5000 3
ri_spent
id Spent_amount budgetid
1 100 2
2 100 2
3 200 3
4)FI_spent
id Spent_amount budgetid
1 100 2
2 100 3
3 200 3
i want to fetch data accourding to or based on first budget table id
below is the query i was trying:
select d.centers as Cost_Center,
ud.BUDGET_ANNUAL_AMOUNT as Annual_Budget,
l.LEAD_ID as Lead_Id,
l.AMOUNT as Lead_Amount,
f.FINANCEADD_ID as Finance_Id,
f.AMOUNT as Finance_Amount
from Cost_centers as d
inner join ANNUAL_BUDGET_BUDGET_CENTER as ud on d.id = ud.BUDGET_ID
inner join RI_DETAILS as l on l.COST_CENTER = d.id
inner join F_RI_DETAILS as f on f.COST_CENTER = d.id
ORDER BY d.id DESC
I want output of the following way:
Id Name ri_id FI_ID RI_Spent_Amount FI_Spent_Amount Annual_Buget
1 test1 1000
2 test2 1 1 100 200 1000
2 test2 2 100 2000
3 test3 3 2 300 100 2000
3 test3 3 200 2000
Any way if possible then please help me.
I want to minus annual budget with spent_amount later.
If possible then help me .
Please Try This Query ,
select b.id ,
b.Budget_name,
y.id,
y.amount_yearly,
r.id,
r.ri_spent,
f.id,
f.Spent_amount
from Budget b
INNER JOIN Yearly_Budget y on y.budgetid =b.id
INNER JOIN ri_spent r on r.budgetid =b.id
INNER JOIN FI_spent f on f.budgetid =b.id
ORDER BY b.id DESC
Could you please use left join instead of inner join. Requirement and sql arent matching so i may be little off. But you can get the idea.
select d.centers as Cost_Center,
ud.BUDGET_ANNUAL_AMOUNT as Annual_Budget,
l.LEAD_ID as Lead_Id,
l.AMOUNT as Lead_Amount,
f.FINANCEADD_ID as Finance_Id,
f.AMOUNT as Finance_Amount
from Cost_centers as d -- I assume this is the budget table
left outer join ANNUAL_BUDGET_BUDGET_CENTER as ud on d.id = ud.BUDGET_ID
left outer join RI_DETAILS as l on l.COST_CENTER = d.id
left outer join
(select sum(FINANCEADD_ID) FINANCEADD_ID,sum(AMOUNT) AMOUNT,id from
F_RI_DETAILS group by id) as f
on f.COST_CENTER = l.id
ORDER BY d.id DESC

MySQL query select from multiple table depending on a certain condition

I have two tables as follow:
table internetclient
(id,full_name,location,phone_number)
table internetclientdetails
(incdid,icid,date_sub, date_exp,isPaid,profile_sub)
the data in two table is as follow:
client
--------------------------------------------------------
id full_name location phone_number
-------------------------------------------------------
4 Joe Amine beirut 03776132
5 Mariam zoue beirut 03556133
client_subscription
--------------------------------------------------------------------------
incdid icid date_sub date_exp isPaid sub_price
----------------------------------------------------------------------------
6 4 2018-01-01 2018-01-30 0 2000
7 5 2017-01-01 2017-01-30 0 1000
8 4 2018-03-01 2018-03-30 1 50000
9 5 2018-05-01 2019-05-30 1 90000
note : incdid stands for internetClientDetailsId
and icid stands for internetClientId
Problem
I want to make a query that return client name along with all details depending on the latest client subscription date, the result should be as follow:
------------------------------------------------------------
full_name client_id date_sub sub_price
------------------------------------------------------------
Joe Amine 4 2018-03-01 50000
Mary 5 2018-05-01 90000
What i am tring
SELECT * FROM client c LEFT JOIN client_subscription c_s on c.id=c_s.client_id
UNION
SELECT * FROM client c RIGHT JOIN client_subscription c_S on c.id=c_s.client_id
WHERE
c.sub_date=(SELECT MAX(sub_date) from client_subscription c_s INNER JOIN client c on c.id=c_s.client_id GROUP BY c_s.client_id
i have been working on it all the night. Any help is appreciated a lot.
To get client_subscription for each client you could use a self join
select c.name, a.client_id, a.date_sub, a.sub_price
from client_subscription a
join (
select client_id, max(date_sub) date_sub
from client_subscription
group by client_id
) b on a.client_id = b.client_id and a.date_sub = b.date_sub
join client c on a.client_id = c.id
order by a.date_sub
Demo
Or using left join
select c.name, a.client_id, a.date_sub, a.sub_price
from client_subscription a
left join client_subscription b on a.client_id = b.client_id and a.date_sub < b.date_sub
join client c on a.client_id = c.id
where b.client_id is null
order by a.date_sub
Demo
Using your updated data set updated queries are
select c.full_name, a.icid, a.date_sub, a.sub_price
from internetclientdetails a
join (
select icid, max(date_sub) date_sub
from internetclientdetails
group by icid
) b on a.icid = b.icid and a.date_sub = b.date_sub
join internetclient c on a.icid = c.id
order by a.date_sub;
select c.full_name, a.icid, a.date_sub, a.sub_price
from internetclientdetails a
left join internetclientdetails b on a.icid = b.icid and a.date_sub < b.date_sub
join internetclient c on a.icid = c.id
where b.icid is null
order by a.date_sub
Updated Demo
Hi try below sample might help you.
DECLARE #tblClient AS TABLE (ID INT , Name varchar(100))
DECLARE #tblClientSub As TABLE (id INT,client_id INT,date_sub DATE,sub_price INT)
INSERT INTO #tblClient (id,Name)
VALUES
(1,'Linda'),
(2,'Mary'),
(3,'Joe')
INSERT INTO #tblClientSub(Id,client_id , date_sub , sub_price)
VALUES
(1,1,'2018/01/01',50),
(2,2,'2018/02/01',50),
(3,2,'2018/03/01',30),
(4,2,'2018/04/01',30),
(5,3,'2018/01/01',50),
(6,3,'2018/07/01',50),
(7,1,'2018/02/01',40)
SELECT c.Id,c.Name,cs.date_sub,cs.sub_price
FROM #tblClient c
CROSS APPLY (SELECT TOP (1)date_sub,sub_price
FROM #tblClientSub
WHERE client_id = c.Id
ORDER BY date_sub DESC) cs
select c.name as 'client_name',cs.client_id,max(cs.sub_date) as 'date_sub',cs.sub_price from client c ,
client_subscription cs where cs.client_id=c.id group by cs.client_id,cs.sub_price;
Try this
SELECT c.Name, c.id , MAX(date_sub), sub_price FROM client c LEFT JOIN client_subscription c_s on c.id=c_s.client_id
GROUP BY c.id
ORDER BY c.id ASC

How do i generate sums from two tables and then join the results together without duplicates in SQL?

To explain more in detail-
I have two tables A & B. Employee ID is the common column between both the tables.
I need to join the 2 tables to compare the FTEs in the 2 tables.
Sample table
Table A:
Emp_ID |S Period |s FTE
1 201701 0.5
1 201701 0.5
2 201702 0.7
3 201702 1
Table B
Emp_ ID |S Period |s FTE
1 201701 1
2 201702 0.5
3 201702 0.7
FTEs need to be summed and grouped by period and emp_id
These 2 tables need to be joined and the result should look something like this
Emp_ID Period FTE (Table A) FTE (Table B)
1 201701 1 1
2 201702 0.7 0.5
3 201702 1 0.7
query
select * from
( select f.Employee_SK , f.period_nk
from adj.PayrollAdjustments p
cross join IA_FACT_Payroll f) pf
left join (select period_nk
, employee_sk
, sum(CalcClinical_FTE) as sum
from IA_FACT_Payroll
group
by Period_NK
, Employee_SK ) f on pf.Employee_SK = f.Employee_SK
left join ( select LibPeriodKey
,PersonnelMasterKey
, sum(clinicalFTE) as sumP
from adj.PayrollAdjustments
group by LibPeriodKey, PersonnelMasterKey) adj on pf.employee_sk = adj.personnelmasterkey
If you do not know if "master tables" for employees and periods exist then you might assume that the summary of the payroll table would cover all employees and periods. If this assumption is true then perhaps this will work:
select
*
from (
select period_nk
, employee_sk
, sum(CalcClinical_FTE) as sum
from IA_FACT_Payroll
group
by Period_NK
, Employee_SK
) iap
left join (
select LibPeriodKey
, PersonnelMasterKey
, sum(ClinicalFTE) as sumP
from adj.PayrollAdjustments
group
by LibPeriodKey
, PersonnelMasterKey
) adj on iap.employee_sk = adj.PersonnelMasterKey and iap.period_nk = adj.LibPeriodKey
However if there is a master table of employees called employee_master and also that there is a master table of periods called periods_master then you could cross join these tables you get a Cartesian product of all employees and all periods allowing you to outer join the calculations like this:
e.g.
select e.id, p.id
from `employee_master` e
cross join `periods_master` p
From a source of employees and periods such as this, you can simply outer join the 2 queries like this:
select
*
from (
select e.id e_id, p.id p_id
from `employee_master` e
cross join `periods_master` p
) ep
left join (
select period_nk
, employee_sk
, sum(CalcClinical_FTE) as sum
from IA_FACT_Payroll
group
by Period_NK
, Employee_SK
) iap on ep.e_id = iap.Employee_SK and ep.p_id = iap.Period_NK
left join (
select LibPeriodKey
, PersonnelMasterKey
, sum(ClinicalFTE) as sumP
from adj.PayrollAdjustments
group
by LibPeriodKey
, PersonnelMasterKey
) adj on ep.e_id = adj.PersonnelMasterKey and ep.p_id = adj.LibPeriodKey

How to get total number of columns in stored procedure?

SELECT
CONVERT(VARCHAR, b.date, 105) AS 'Date',
m.menucost * (Sum(bm.qty)) AS 'Total'
FROM
billmaster b
LEFT JOIN
billmenumapping bm ON bm.mapbillid = b.billid
LEFT JOIN
menumaster m ON m.menuid = bm.mapmenuid
WHERE
b.date BETWEEN '2015/02/22' AND '2015/02/25'
GROUP BY
b.Date, m.menucost
This code returns the following result:
Date Total
-------------------
23-02-2015 40.00
22-02-2015 40.00
22-02-2015 1800.00
I need the output in a way where totals of date 22-02-2015 dates should be combined and only one result should be given as below. Sum of the total column should be done according to the respective dates.
Date Total
--------------------
23-02-2015 40.00
22-02-2015 1840.00
Please help.
Try this:
SELECT Date,SUM(Total) FROM
(SELECT CONVERT(VARCHAR, b.date, 105) AS 'Date',
m.menucost * (Sum(bm.qty)) AS 'Total'
FROM billmaster b
LEFT JOIN billmenumapping bm
ON bm.mapbillid = b.billid
LEFT JOIN menumaster m
ON m.menuid = bm.mapmenuid
WHERE b.date between '2015/02/22' and '2015/02/25'
GROUP BY b.Date,m.menucost) TempTable
GROUP BY Date

Divide a query result having multiple records with another query result having multiple records in mysql

I have two queries giving two sets of result, i want to divide one query's result with another.
Here is my first query :
SELECT COUNT(*)
FROM survey_event_answers a JOIN survey_events e ON a.eventid = e.eventid
WHERE e.event_status = 'Closed' AND
e.survey_date BETWEEN '2013-05-01' AND '2014-01-31' AND
a.response_options IN (10,11) AND a.questionid = 7
GROUP BY MONTH(e.survey_date) DESC;
Here is the result of this query :
279
443
664
743
785
1312
1085
915
231
Here is my another query :
SELECT COUNT(*),e.survey_date
FROM `survey_event_answers` a INNER JOIN survey_events e ON a.eventid = e.eventid
WHERE e.event_status='Closed' AND
e.survey_date BETWEEN '2013-05-01' AND '2014-01-31' AND
a.questionid=7
GROUP BY MONTH(e.survey_date) DESC
Here is the query result :
351
539
826
926
984
1654
1378
1165
844
I want that first row of first result set should divide by first row of second row set.
Please help me out how can i do this.
Thanks
is this what are you looking for?
SELECT rd1.r1/rd2.r2 `result`
FROM (
SELECT COUNT(*) r1,MONTH(e.survey_date) d1
FROM `survey_event_answers` a
INNER JOIN survey_events e
ON (a.eventid = e.eventid)
WHERE e.event_status='Closed' AND e.survey_date BETWEEN '2013-05-01' AND '2014-01-31'
AND a.response_options IN (10,11) AND a.questionid=7
GROUP BY MONTH(e.survey_date) DESC ) rd1
JOIN (
SELECT COUNT(*) r2, MONTH(e.survey_date) d2
FROM `survey_event_answers` a
INNER JOIN survey_events e
ON (a.eventid = e.eventid)
WHERE e.event_status='Closed' AND e.survey_date BETWEEN '2013-05-01' AND '2014-01-31'
AND a.questionid=7
GROUP BY MONTH(e.survey_date) DESC ) rd2
ON rd1.d1=rd2.d2
You could do:
SELECT SUM(IF(a.response_options IN (10,11), 1, 0))/COUNT(*)
FROM survey_event_answers a
JOIN survey_events e
ON a.eventid = e.eventid
WHERE e.event_status = 'Closed'
AND e.survey_date BETWEEN '2013-05-01' AND '2014-01-31'
AND a.questionid = 7
GROUP BY MONTH(e.survey_date) DESC;
This may not be fast (but it is faster than doing the query twice and joining the results), but probably do what you want (ratio of answers 10 or 11). You can add the MONTH(e.survey_date) as a second column.