SQL select sum from multiple tables without JOIN - sql

I have several tables with the same structure. How can I select SUM(field) from these tables without JOIN (just simply union the tables)?
For example, if I run:
SELECT SUM(views) FROM tb1, tb2 WHERE 1
It tells me "Column 'views' in field list is ambiguous".
Is there a way to use UNION?

I think this should get you:
SELECT SUM(views)
FROM (
SELECT views FROM table1
UNION ALL
SELECT views FROM table2
) A
The reason you're getting an error is because you're making a Cartesian product (all rows in one table are matched to all rows in the other table), and since both tables have a view column, it doesn't know which you're taking about. However, that Cartesian join will (probably) not give you the sum you're looking for.

If the structure is the same:
SELECT SUM(views)
FROM (tb1 UNION tb2)
WHERE 1
If that doesn't work, try (I don't have a mysql handy to test it):
SELECT SUM(views)
FROM (
(SELECT views FROM tb1)
UNION
(SELECT views FROM tb2)
)
WHERE 1

SELECT SUM(views) FROM
(
SELECT views FROM tb1
UNION ALL
SELECT views FROM tb2
) t

Related

Adding sum values from two different tables

How can i achieve this. T2 is linked with another table which contains order details like customer name, country and classification. They have an inner join.
T1 is linked to T2 only via order code and order item.
Assuming that both tables report the same set of order numbers, we can try joining two subqueries each of which finds the sums in the respective tables:
SELECT
t1.ORDER_NUM,
t1.ORDER_ITEM,
t1.PRODUCED + t2.PRODUCED AS PRODUCED
FROM
(
SELECT ORDER_NUM, ORDER_ITEM, SUM(PRODUCED) AS PRODUCED
FROM table1
GROUP BY ORDER_NUM
) t1
INNER JOIN
(
SELECT ORDER_NUM, ORDER_ITEM, SUM(NET_IN - NET_OUT) AS PRODUCED
FROM table2
GROUP BY ORDER_NUM
) t2
ON t1.ORDER_NUM = t2.ORDER_NUM AND
t1.ORDER_ITEM = t2.ORDER_ITEM
ORDER BY
t1.ORDER_NUM,
t1.ORDER_ITEM;
Note that the above is not necessarily an ideal approach, because a given order/item combination in one table might not appear in the other table. A better approach would be to start the query with a reference table containing all orders and items. That failing, we could convert the above to a full outer join.
I think a simple approach is union all:
select ordernum, orderitem, sum(produced) as produced
from ((select ordernum, orderitem, produced
from table1
) union all
(select ordernum, orderitem, netout
from table2
)
) t12
group by ordernum, orderitem;
This has two advantages over pre-aggregating and using joins:
It keeps all order/item pairs, even those that appear in one table.
If you add a where claus to the outer query, SQL Server is likely to "project" that into the subqueries.
Try for bellow query also
select t1.order_num,t1.order_item,sum(t1.produced)+(select sum(net_in) from t2)-(select sum(t2.net_out) from t2)PRODUCED
from t1
group by t1.order_num,t1.order_item
if you have wanted the only sum from another table that time you have used select query and do the sum of a particular column.

Big Query: SQL JOIN with column prefix

I have two tables in Google Big Query. One table is kind of a product catalogue (1:1), while the second one is product related information (1:n). For a query I'm joining both. But the joins fails since the column pid and some others are present in both tables.
#standardSQL
SELECT tbl1.*, tbl2.* FROM (
SELECT * FROM `my_project.my_dataset.my_table_1`
) AS tbl1
LEFT JOIN ( SELECT * FROM `my_project.my_dataset.my_table_2`) AS tbl2
ON tbl1.pid = tbl2.pid
WHERE tbl1.category LIKE '111002%'
Idea 1: How to select * without the duplicated columns (that I can put in manually).
Idea 2: How to provide a left/right prefix for the columns in the join?
Any help is appreciated.
To avoid duplicating pid from both sides of the join, use a USING clause instead:
#standardSQL
SELECT * FROM (
SELECT * FROM `my_project.my_dataset.my_table_1`
) AS tbl1
LEFT JOIN ( SELECT * FROM `my_project.my_dataset.my_table_2`) AS tbl2
USING(pid)
WHERE tbl1.category LIKE '111002%'
To prefix the column names from both sides of the join, use a reference to the tables in the select list instead of applying .* to them:
#standardSQL
SELECT tbl1, tbl2 FROM (
SELECT * FROM `my_project.my_dataset.my_table_1`
) AS tbl1
LEFT JOIN ( SELECT * FROM `my_project.my_dataset.my_table_2`) AS tbl2
USING(pid)
WHERE tbl1.category LIKE '111002%'
The columns resulting from the query will be tbl1 and tbl2, which are STRUCTs containing the columns from each of those tables as fields.

how can we select data from two or more tables if similar data is not present in both tables(without join)

I need solution for this type query.Means this query is not real but I need to fetch data like this:(except join and union)
select a b,c
from (table1 or table2)
where name="rohit";
it's simple to do with union
select *
from t1
where t1.name='a'
union (all)
select *
from t2
where t2.name='a'
If union and join is not allowed you can try select both table and create kind of union via GROUP BY trick. Like this
select *
from t1, t2
where t1.name='a' or t2.name='a'
group by (case t1.name
when 'a' then CONCAT('t1',t1.id)
else CONCAT('t2',t2.id) end case)
Haven't tested though. sqlfiddle.com somehow doesn't work showing errors when I try to execute a query like this

Create View of two identical tables from two seperate systems to return only unique records

I have two systems running the same software off identical databases. For reporting, I need to report on the ticket tables.
I linked the two servers and created a union between the two ticket tables but I am still getting duplicate records. The software does replicate ticket data betwen the two systems however this is a report for "pre" replication which means this
I need ALL tickets in ticket table A and I need only records from ticket table B that I do not already have. The ticket number is unique in this instance. I am using several colums from these tables like, vehicle ID, Customer Name, Price, Quantity, etc. And many in formulas at well. To name them all would really be extensive. Is there another way to take ALL columns from both tables into a view but only see distnct records
I tried to create the view like this:
CREATE VIEW vw_combinedtickettable as
SELECT *
FROM dbo.Ticket
UNION
SELECT * from LinkedServer.Database2.dbo.ticket
Thinking using just union and not union all would work and it isn't.
Any help would be great.
SELECT *
FROM dbo.Ticket
UNION ALL
SELECT *
FROM LinkedServer.Database2.dbo.ticket
WHERE ticketNumber NOT IN
(
SELECT ticketNumber
FROM dbo.Ticket
)
you could try:
CREATE VIEW vw_combinedtickettable AS
SELECT * FROM dbo.Ticket t1
UNION ALL
SELECT t2.* FROM dbo.Ticket t1
LEFT JOIN LinkedServer.Database2.dbo.ticket t2
ON t1.id = t2.id
AND t1.id IS NULL
Hope this helps!

How do I merge data from two tables in a single database call into the same columns?

If I run the two statements in batch will they return one table to two to my sqlcommand object with the data merged. What I am trying to do is optimize a search by searching twice, the first time on one set of data and then a second on another. They have the same fields and I’d like to have all the records from both tables show and be added to each other. I need this so that I can sort the data between both sets of data but short of writing a stored procedure I can’t think of a way of doing this.
Eg. Table 1 has columns A and B, Table 2 has these same columns but different data source. I then wan to merge them so that if a only exists in one column it is added to the result set and if both exist it eh tables the column B will be summed between the two.
Please note that this is not the same as a full outer join operation as that does not merge the data.
[EDIT]
Here's what the code looks like:
Select * From
(Select ID,COUNT(*) AS Count From [Table1]) as T1
full outer join
(Select ID,COUNT(*) AS Count From [Table2]) as T2
on t1.ID = T2.ID
Perhaps you're looking for UNION?
IE:
SELECT A, B FROM Table1
UNION
SELECT A, B FROM Table2
Possibly:
select table1.a, table1.b
from table1
where table1.a not in (select a from table2)
union all
select table1.a, table1.b+table2.b as b
from table1
inner join table2 on table1.a = table2.a
edit: perhaps you would benefit from unioning the tables before counting. e.g.
select id, count() as count from
(select id from table1
union all
select id from table2)
I'm not sure if I understand completely but you seem to be asking about a UNION
SELECT A,B
FROM tableX
UNION ALL
SELECT A,B
FROM tableY
To do it, you would go:
SELECT * INTO TABLE3 FROM TABLE1
UNION
SELECT * FROM TABLE2
Provided both tables have the same columns
I think what you are looking for is this, but I am not sure I am understanding your language correctly.
select id, sum(count) as count
from (
select id, count() as count
from table1
union all
select id, count() as count
from table2
) a
group by id