select
a.ClientID,
f.Currency,
a.OrganizationName,
COALESCE(sum(b.GrandTotal),0) as SaleGrandTotal,
COALESCE(sum(g.AmountReceived),0) as AmountReceived,
COALESCE(sum(b.GrandTotal - g.AmountReceived),0) as SaleBalanceRemaining,
COALESCE(sum(d.GrandTotal), 0) as PurchaseGrandTotal,
COALESCE(sum(e.AmountPaid), 0) as AmountPaid,
COALESCE(sum(d.GrandTotal - e.AmountPaid),0) as PurchaseBalanceRemaining,
COALESCE(sum(b.GrandTotal - g.AmountReceived),0) - COALESCE(sum(d.GrandTotal - e.AmountPaid),0) as Total
from na_clients as a
join na_currency as f
left join na_transaction as b
on a.ClientID = b.ClientID and b.CurrencyID = f.CurrencyID and b.IsActive = 1
left join na_recoverylogs as g
on b.TID = g.TID
left join na_purchase as d
on a.ClientID = d.ClientID and d.CurrencyID = f.CurrencyID and d.IsActive = 1
left join na_purchaselogs as e
on e.PID = d.PID
group by a.OrganizationName,f.Currency
order by a.OrganizationName
I am using multiple currency like dollar,CNY,rupees.
It was working fine but today i noticed sum() double value like b.GrandTotal should be 11500 but its return 23000
Table Client:
clientid,name,organizationName
1,client1,OrgName
2,client2,OrgName
Table Currency:
currencyid,cname
1,Dollar
2,Rupees
Table Transaction:
tid,clientid,currencyid,grandTotal,amountReceived,balanceremaining
1,1,1,11000,0,11000
2,1,1,500,0,500
Table recoveryLogs: // Another Error Here
id,tid,amountreceived
1,1,0
2,2,0
3,2,2000 // Again sum() multiply value - because of PID 2 is repeating
Table Purchase:
pid,clientid,currencyid,grandTotal,amountPaid,balanceRemaining
1,1,1,25000,0,25000
1,2,2,2,3000,1000,2000
Now I am using sum(b.grandTotal) instead of 11500 it return 23000
Table PurchaseLogs: // Another Error Here
id,pid,amountpaid
1,1,0
2,2,1000
3,1,1000 // Again sum() multiply value - because of PID 1 is repeating
So result should be:
Client: Client1
SaleGrandTotal: 11500
AmountReceived: 0
SaleBalanceRemaining: 11500
PurchaseGrandTotal: 25000
AmountPaid: 0
PurchaseBalanceRemaining: 25000
Total Amount: -13500
But result i get:
Client: Client1
SaleGrandTotal: 23000
AmountReceived: 0
SaleBalanceRemaining: 23000
PurchaseGrandTotal: 50000
AmountPaid: 0
PurchaseBalanceRemaining: 50000
Total Amount: -27000
If i remove purchase clause(d and e) or transaction(b and g) clause from query it's working fine individually.
The reason data is doubling is your ClientID has different occurrences in Transaction and Purchase tables and hence not a 1-to-1 match. ClientID = 1 and CurrencyID = 1 appears twice in Transaction and only once in Purchase. When you join the tables, a combination set of 1 x 2 = 2 ClientID records result with some fields repeating data. Thus, summing will double for repeat entries. As illustration:
Transaction Data | Purchase Data
row1: 1,1,1,11000,0,11000 | 1,1,1,25000,0,25000
row2: 2,1,1,500,0,500 | 1,1,1,25000,0,25000
Consider separating the aggregation between both tables using derived tables. Then, join the four underlying aggregates (transaction, purchase, recovery log, purchase log) for final query. The join will match 1-to-1 if you aggregate, grouping on ClientID and CurrencyID, TID and PID.
SELECT
transAgg.ClientID, transAgg.Currency, transAgg.OrganizationName,
transAgg.SaleGrandTotal, recovLogAgg.SumOfAmtReceived,
(transAgg.SaleGrandTotal - recovLogAgg.SumOfAmtReceived) as SaleBalanceRemaining,
purchAgg.PurchaseGrandTotal, purchLogAgg.SumOfAmtPaid,
(purchAgg.PurchaseGrandTotal - purchLogAgg.SumOfAmtPaid) as PurchaseBalanceRemaining,
((transAgg.SaleGrandTotal - recovLogAgg.SumOfAmtReceived) -
(purchAgg.PurchaseGrandTotal - purchLogAgg.SumOfAmtPaid)) As [Total]
FROM
(SELECT
a.ClientID, f.CurrencyID, f.Currency, a.OrganizationName,
COALESCE(sum(b.GrandTotal),0) as SaleGrandTotal
FROM na_clients as a
INNER JOIN na_currency as f
LEFT JOIN na_transaction as b
ON a.ClientID = b.ClientID
AND b.CurrencyID = f.CurrencyID
AND b.IsActive = 1
GROUP BY a.ClientID, a.OrganizationName, f.CurrencyID, f.Currency
ORDER BY a.OrganizationName) As transAgg
INNER JOIN
(SELECT
a.ClientID, f.CurrencyID, f.Currency, a.OrganizationName,
COALESCE(sum(d.GrandTotal), 0) as PurchaseGrandTotal
FROM na_clients as a
INNER JOIN na_currency as f
LEFT JOIN na_purchase as d
ON a.ClientID = d.ClientID
AND d.CurrencyID = f.CurrencyID
AND d.IsActive = 1
GROUP BY a.ClientID, a.OrganizationName, f.CurrencyID, f.Currency
ORDER BY a.OrganizationName) As purchAgg
ON transAgg.ClientID = purchAgg.ClientID
AND transAgg.CurrencyID = purchAgg.CurrencyID
INNER JOIN
(SELECT
g.TID, COALESCE(sum(g.AmountReceived),0) As SumOfAmtReceived
FROM na_recoverylogs as g
GROUP BY g.TID) As recovlogAgg
ON transAgg.TID = recovlogAgg.TID
INNER JOIN
(SELECT
e.PID, COALESCE(sum(e.AmountPaid),0) As SumOfAmtPaid
FROM na_purchaselogs as e
GROUP BY e.PID) As purchlogAgg
ON purchAgg.PID = purchlogAgg.PID
I have a query where I try to retrieve the number of rows but in my case drops as result 1 on each time. I suppose that is a join problem and I don't kniw how to handle this
SELECT
COUNT(*) AS summe
FROM
feeds
LEFT JOIN cat_product cp
ON cp.product_id = feeds.productid
WHERE 1 = 1
AND cp.price BETWEEN 950
AND 1450
AND cp.ram_cap BETWEEN 5
AND 11
AND feeds.tdcategoryname LIKE '%Laptop%'
AND feeds.brand IN ('Dell', 'Lenovo', 'Acer', 'Asus')
GROUP BY cp.product_id
Try this, not sure if you are using MySQL or MSSQL. Since you LEFT JOIN there is a possibility that a value is NULL. In MSSQL if a NULL value is accounted for the the result will be NULL Always when using a aggregated function like COUNT.
For MySQL
SELECT
COUNT(IFNULL(cp.Procuct_id,0)) AS summe
FROM
feeds
LEFT JOIN cat_product cp
ON cp.product_id = feeds.productid
WHERE 1 = 1
AND cp.price BETWEEN 950
AND 1450
AND cp.ram_cap BETWEEN 5
AND 11
AND feeds.tdcategoryname LIKE '%Laptop%'
AND feeds.brand IN ('Dell', 'Lenovo', 'Acer', 'Asus')
Ok, what I'm trying to do is try and get unique values from one table that span 4 separate columns.
For example, I have this below query which works correctly on one of the columns..
SELECT
rest.cuisine1, c.name
FROM
specials
INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id
INNER JOIN cuisine AS c ON rest.cuisine1=c.id
WHERE
dateend >= CURDATE()
AND
(specials.state='VIC' OR specials.state = 'ALL')
AND
specials.status = 1
AND
rest.status = 1
GROUP BY
c.id;
Now, rest.cuisine1 is one of the columns that contain the data. As expected this query returns unique values from that column only. The below being an example of what is returned:
12 Cafe
18 Asian
29 Coffee
There are 3 more columns in that table, those being:
rest.cuisine2
rest.cuisine3
rest.cuisine4
I could run the above query 4 times (one on each column) and THEN run the values through PHP to get only unique values from the 4 different result sets, however I was wanting to find out if I can get what I want all in the one query.
try this
SELECT
rest.cuisine1, c.name ,rest.cuisine2 , rest.cuisine3, rest.cuisine4
FROM
specials
INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id
INNER JOIN cuisine AS c ON rest.cuisine1=c.id
INNER JOIN cuisine AS c2 ON rest.cuisine2=c2.id
INNER JOIN cuisine AS c3 ON rest.cuisine3=c3.id
INNER JOIN cuisine AS c4 ON rest.cuisine4=c4.id
WHERE
dateend >= CURDATE()
AND
(specials.state='VIC' OR specials.state = 'ALL')
AND
specials.status = 1
AND
rest.status = 1
GROUP BY
c.id;
This answer is based off of MahmoudGamal's answer he posted in a comment, which he deleted for some reason.
I used the below..
SELECT
c.id, c.name
FROM
specials
INNER JOIN restaurant AS rest ON specials.restaurantid=rest.id
INNER JOIN cuisine AS c ON c.id IN (rest.cuisine1, rest.cuisine2, rest.cuisine3, rest.cuisine4)
WHERE
dateend >= CURDATE()
AND
(specials.state='VIC' OR specials.state = 'ALL')
AND
specials.status = 1
AND
rest.status = 1
GROUP BY
c.id;
A Company has many Reviews which has Rating Column itself.
CompID Ratig
12 3
13 3
17 4
22 4
23 5
24 3
28 3,2
This is what I need to be set to each company by id. Now Rating In Company Column is NULL.
I've written something like this:
UPDATE Companies c
JOIN Reviews r on c.CompanyID = r.CompanyID
SET c.Rating = AVG(r.rating)
group by r.CompanyID
This should do what you want using a simple nested query, in this case probably simpler than a JOIN.
UPDATE Companies
SET Rating =
(SELECT AVG(Rating)
FROM Ratings
WHERE Companies.CompanyId = Ratings.CompId)
Simple SQLfiddle demo here.
EDIT: If you really want to use a JOIN/UPDATE FROM, it'd look something like this;
UPDATE c
SET c.Rating = r.Rating
FROM Companies c
JOIN (SELECT AVG(Rating) Rating, CompID FROM Ratings GROUP BY CompId) r
ON c.CompanyId = r.CompId
At least to me, somewhat more complicated to read, and afaik it only works on SQL Server, but here's the SQLfiddle for that too :)
UPDATE ComisionesxColaboradorxLineaPrescripciones
SET CANTIDAD_PRODUCTOS_CORE_CUMPLE = CANTIDAD
FROM #ComisionesxColaboradorxLineaPrescripciones ComisionesxColaboradorxLineaPrescripciones
INNER JOIN
(SELECT TAB_L.COD_COLAB AS COD_COLAB,TAB_L.TIPO_COLABORADOR AS TIPO_COLABORADOR, COUNT(TAB_P.COD_SEG) AS CANTIDAD
FROM #ComisionesxColaboradorxLineaPrescripciones TAB_L
INNER JOIN #ComisionesxColaboradorxLineaxProductoPrescripciones TAB_P
ON TAB_L.COD_COLAB=TAB_P.COD_COLAB AND
TAB_L.TIPO_COLABORADOR=TAB_P.TIPO_COLABORADOR
GROUP BY TAB_L.COD_COLAB,TAB_L.TIPO_COLABORADOR
) AGRUPADO
ON ComisionesxColaboradorxLineaPrescripciones.COD_COLAB = AGRUPADO.COD_COLAB AND
ComisionesxColaboradorxLineaPrescripciones.TIPO_COLABORADOR = AGRUPADO.TIPO_COLABORADOR
My query is shown below
select count(au.agentId), count(mr.agentId)
from agents a
left join assignunits au on au.agentId=a.id
left join assignmarketreport mr on mr.agentId=a.id
where a.adminsId='0'
and a.id='29' group BY `mr`.`agentId`, au.agentId ASC
I am getting value of count(au.agentId) same as value of count(mr.agentId).
What I want:
For the below sample data
assignunits
agentId status
2 Y
2 Y
assignmarketreport
agentId status
2 Y
2 Y
2 Y
agents
agentId adminsId
2 0
Now count(mr.agentId) should return 3
and count(au.agentId) should return 2
try this:
select au_agentId,mr_agentId
from
(select a.agentId,count(au.agentId) as au_agentId
from agents a
left join assignunits au
on au.agentId=a.agentId
where a.adminsId='0'
group by a.agentId )au
join
(select a.agentId,count(mr.agentId) as mr_agentId
from agents a
left join assignmarketreport mr
on mr.agentId=a.agentId
where a.adminsId='0'
group by a.agentId)mr
on au.agentId=mr.agentId
SQl fiddle demo
Try the following,
SELECT b.totalAgentUnits, c.totalAgentReport
FROM Agents a
LEFT JOIN
(
SELECT agentID, COUNT(agentID) totalAgentUnits
FROM assignunits
GROUP BY agentID
) b ON a.agentID = b.agentID
LEFT JOIN
(
SELECT agentID, COUNT(agentID) totalAgentReport
FROM assignmarketreport
GROUP BY agentID
) c ON a.agentID = c.agentID
first query a 3 counts count(units), count(marketport),count(agents) and insert them into a count
count(counts `count(units), count(marketport),count(agents)`)
after it you may set up a php loop to get each data and display in each table
for($i=0;$count<3;$i++){
if($i==1){
//table 1
}
elseif($i==2){
//table 2
}
elsE{
//last table
}
}
an opinion only thanks