How to get the Sum from three tables? [duplicate] - sql

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to get Sum from two tables?
I have three table first "products" second "items" third "sales"
The first and second tables have the same columns('code','quantity') but the third table has ('code','name') now I want sum quantity from first and second but want also want get name from third table which code is equal.
check my code
Select code, sum(qtd),name
from ( select a.code, a.qtd from product a
union all select b.code, b.qtd from items b
union all select c.name from sales c where b.code=c.code
)
group by code
first two giving me perfect values but third fiction giving error not showing also names.

Hum....
SELECT
sales.name,
(SELECT SUM(products.quantity) FROM products WHERE products.code = sales.code) as products.quantity,
(SELECT SUM(items.quantity) FROM items WHERE items.code = sales.code) as items_quantity,
FROM sales

When using UNION be sure that the columns you want to combine matches with each SELECT statement. The first two SELECT statement works fine because they have the same number of columns. The third one failed because it has only one column.
The following are basic rules for combining the result sets of two (or more) queries by using UNION:
The number and the order of the columns must be the same in all queries.
The data types must be compatible.
From your query, I think you want like this,
SELECT a.code, b.name, SUM(a.qtd) totalSUM
FROM product a
INNER JOIN sales b
ON a.code = b.code
GROUP BY a.code, b.name
UNION
SELECT a.code, b.name, SUM(a.qtd) totalSUM
FROM items a
INNER JOIN sales b
ON a.code = b.code
GROUP BY a.code, b.name

I think you want to do something like this, though it's not clear what the actual requirements are:
select code = t1.code ,
name = t2.name ,
qtd = t1.qtd
from ( select code = t.code ,
qtd = sum( t.qtd )
from ( select a.code, a.qtd from product a
union all select b.code, b.qtd from items b
) t
group by t.code
) t1
join sales t2 where t2.code = t1.code
Cheers!

Related

SQL joined tables are causing duplicates

So table A is an overall table of policy_id information, while table b is policy_id's with claims attached. Not all of the id's in A exist in B, but I want to join the two tables and sum(total claims).
The issue is that the sum is way higher than the actual sum within the table itself.
Here is what I've tried so far:
select a.policy_id, coalesce(sum(b.claim_amt), 0)
from database.table1 as a
left join database2.table2 as b on a.policy_id = b.policy_id
where product_code = 'CI'
group by a.policy_id
The id's that don't exist in b show up just fine with a 0 next to them, it's the ones that do exist where the claim_amt's seem like they're being duplicated heavily in the sum.
I suspect your policy_id in table1 are not unique and that leads to the doubled,tripled ,etc. amounts
You could aggregate the sums from table2 in a CTE to get around this.
WITH CTE AS (
SELECT
policy_id
coalesce(sum(claim_amt), 0) as sum_amt
FROM database2.table2
group by policy_id
)
select a.policy_id, b.sum_amt
from database.table1 as a
left join CTE as b on a.policy_id = b.policy_id
where product_code = 'CI'

Top nth of a report with rest as other

I have a query that shows total amount by supplier. I want a report where the top 9 are shown and the rest is added together under an "other" supplier. Thus the detail shows top 9 suppliers, other groups the rest and the total on the report includes all.
I cant get the top 9 but how to I get the "other"
I use MS Access 2007
EDIT:
I also need to add a company name that is in another register. t_costed has the value, linked to t_register_2bre that has the company, linked to t_contacts_company that had the company name.
I know the amount of columns returned by the select query must be equal in the two unioned queries but I'm struggling with the INNER JOIN.
You could use a union query in the following way:
select top 9 t.amount
from table1 t
order by t.amount desc
union all
select sum(u.amount)
from table1 u
where
u.amount <
(
select min(v.amount)
from
(select top 9 w.amount from table1 w order by w.amount desc) v
)
Here, change all references to table1 with the name of your table.
EDIT:
With the additional information provided in your question, I would suggest the following (untested) SQL:
select top 9 c.company, t.amount
from
(t_costed t inner join t_register_2bre r on t.eventidbre = r.id_bre)
inner join t_contacts_company c on r.defaulting_partyid = c.id_contacts_company
order by t.amount desc
union all
select "Others" as company, sum(u.amount)
from t_costed u
where
u.amount <
(
select min(v.amount)
from
(select top 9 w.amount from t_costed w order by w.amount desc) v
)

Select SUM from multiple tables

I keep getting the wrong sum value when I join 3 tables.
Here is a pic of the ERD of the table:
(Original here: http://dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png )
Here is the query:
select SUM(gpCutBody.actualQty) as cutQty , SUM(gpSewBody.quantity) as sewQty
from jobOrder
inner join gpCutHead on gpCutHead.joNum = jobOrder.joNum
inner join gpSewHead on gpSewHead.joNum = jobOrder.joNum
inner join gpCutBody on gpCutBody.gpCutID = gpCutHead.gpCutID
inner join gpSewBody on gpSewBody.gpSewID = gpSewHead.gpSewID
If you are only interested in the quantities of cuts and sews for all orders, the simplest way to do it would be like this:
select (select SUM(gpCutBody.actualQty) from gpCutBody) as cutQty,
(select SUM(gpSewBody.quantity) from gpSewBody) as sewQty
(This assumes that cuts and sews will always have associated job orders.)
If you want to see a breakdown of cuts and sews by job order, something like this might be preferable:
select joNum, SUM(actualQty) as cutQty, SUM(quantity) as sewQty
from (select joNum, actualQty, 0 as quantity
from gpCutBody
union all
select joNum, 0 as actualQty, quantity
from gpSewBody) sc
group by joNum
Mark's approach is a good one. I want to suggest the alternative of doing the group by's before the union, simply because this can be a more general approach for summing along multiple dimensions.
Your problem is that you have two dimensions that you want to sum along, and you are getting a cross product of the values in the join.
select joNum, act.quantity as ActualQty, q.quantity as Quantity
from (select joNum, sum(actualQty) as quantity
from gpCutBody
group by joNum
) act full outer join
(select joNum, sum(quantity) as quantity
from gpSewBody
group by joNum
) q
on act.joNum = q.joNum
(I have kept Mark's assumption that doing this by joNum is the desired output.)

Using the value in a row to fetch data for another column for the same row [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Geting value count from an Oracle Table
I have a simple query on 2 tables A and B
Table A
========
LOCATION, NAME
Table B
========
LOCATION, SKU
The query is:
select A.LOCATION, B.SKU
from A, B
where A.Location = B.Location
In the result of this query, I would like to add another column with the count of all locations in B which have the same SKU as returned by the above query.
I'm making the assumption here that you want A.Location, B.SKU and then the count of B.Location values that exist for B.SKU. If that is true then it should just be a left outer join:
Select A.Location, B.SKU, Count(B.Location)
from
B Left outer join A on (B.Location = A.Location)
Where B.SKU in ( /* value */ )
group by A.Location, B.SKU
The only thing to note here is that for each A.Location returned for a SKU, you will see a line with that location, the SKU and the repeated count:
Location1, ABC, 100
Location2, ABC, 100
Location3, ABC, 100
You should look into the Oracle analytical functions. This allows you to add aggregate columns (such as count) without grouping the data.
So, perhaps something like this:
select A.LOCATION, B.SKU, count(b.location) over (partition by sku) as locskucount
from A, B
where A.Location=B.Location
order by a.location
This will give you a count of locations per SKU.

Joining to the same table in SQL - SQL Server 2008

I have the following table:
ID Type Description IDOfSystem
--------------------------------
1000 Company Company Item NULL
1010 System System Item NULL
1020 Company NULL 1010
I have System and Company Items. I need to write a select query that gets all the company items and system items UNLESS if a company item has a value in IDOfSystem I need to exclude that system item and get the description from the system item.
So, given the above table, the SQL select should return rows 1000, 1020 (with "System Item") as the description.
If 1020 didn't exist, I'd simply get 1000 and 1010.
I guess I can break this up into multiple queries and do a UNION. I tried to do a left outer join on the same table but couldn't get the description from the system row.
Any help?
SELECT ID, Type, Description
FROM MyTable AS A
WHERE IDOfSystem IS NULL AND NOT EXISTS (SELECT *
FROM MyTable AS B
WHERE B.IDOfSystem = A.ID)
UNION ALL
SELECT A.ID, A.Type, B.Description
FROM MyTable AS A INNER JOIN MyTable AS B ON A.IDOfSystem = B.ID
WHERE IDOfSystem IS NOT NULL
What I'm doing is first selecting all rows that don't have a referenced system, and aren't used as some other rows system.
Then I'm doing a union with another query that finds all rows with a referenced system, and joining in the system to grab it's description.
SELECT
Companies.ID
,Companies.Type
,COALESCE(Systems.Description, Companies.Description) as Description
FROM YourTable Companies
LEFT OUTER JOIN YourTable Systems on Systems.ID = Companies.IDOfSystem
WHERE NOT EXISTS
(
SELECT * FROM YourTable T3 WHERE T3.IDOfSystem = Companies.ID
)
Here it is running on SEDE.
This approach uses a self join to look up the corresponding system's description. A separate subquery filters out the referenced systems.
select yt1.Id
, yt1.Type
, coalesce(yt2.Description, yt1.Description) as Description
from YourTable yt1
left join
YourTable yt2
on yt1.type = 'Company'
and yt2.type = 'System'
and yt2.ID = yt1.IDOfSystem
where yt1.type in ('System', 'Company')
and not exists
(
select *
from YourTable yt3
where yt1.type = 'System'
and yt3.type = 'Company'
and yt1.ID = yt3.IDOfSystem
)
Working example at SE Data.
I'm sure there are better ways of doing this, but try:
SELECT A.Id, A.Type, ISNULL(A.Description,B.Description) Description, A.IDOfsystem
FROM YourTable A
LEFT JOIN YourTable B
ON A.IDOFSystem = B.ID
WHERE A.ID NOT IN (SELECT IDOfsystem FROM YourTable WHERE IDOfsystem IS NOT NULL)