Query two tables as one from different namespaces - sql

I have two tables in a PostgreSQL database that contains two tables that differ only by namespace: Japan.Revenue and Korea.Revenue. I want to query them as there is one table only.
E.g
SELECT productgroup, sum(transactionvalue)
FROM ???? (Something that combines the two tables)
Group by productgroup where ....
How do I do that?
I need the Korea and Japan results combined. So far I did sent 2 queries and combined the result in the app. There must be a better way

You need to fully-qualify the table names and union the results.
It's possible to do more than a simple select for the inner queries, but because you are doing an aggregation, you need to do it outside.
https://www.postgresql.org/docs/current/static/queries-union.html
SELECT productgroup, sum(transactionvalue)
FROM (
SELECT * FROM Japan.Revenue
UNION ALL
SELECT * FROM Kora.Revenue
) sub
GROUP BY productgroup
WHERE ....
;
Edit: Now using UNION ALL from comments below.

try this:
SELECT productgroup, sum(transactionvalue)
FROM korea
Group by productgroup
union all
SELECT productgroup, sum(transactionvalue)
FROM japon
Group by productgroup
when you have same column with same type best way to combine is union
and you can group by it outside of select too.

Related

Return result of three SQL queries in one SQL view

Is it possible to return results of three separate SQL queries in one view?
I would like to create an "Initial data" view, with some stats from my DB, returning three counts() from different tables. Something like that:
CREATE VIEW initial AS
SELECT count(*) AS albums_count FROM albums,
SELECT count(*) AS artists_count FROM artists,
SELECT count(*) AS tracks_count FROM tracks;
I do not mind if the results are in rows or columns. UNION would kind of work - but it does not make sense from performance perspective.
(I know I could just do three separate requests from the frontend or have that combined in my backend code but I use PostgREST as my API, and I do not want to make 3 separate "initial" requests when my website loads.)
You can union the counts with adding a column for the count type for each, such as
SELECT count(*) as Quantity, 'albums' as countType FROM albums union all
SELECT count(*), 'artists' FROM artists union all
SELECT count(*), 'tracks' FROM tracks;
If you want 3 columns you can just select them as derived tables:
select
(SELECT count(*) FROM albums) AS albums_count,
(SELECT count(*) FROM artists) AS artists_count,
(SELECT count(*) FROM tracks) AS tracks_count;

How to pass the output of the subquery into the main query so it could count the items from a separate table

Below is what I am trying to achieve. I have a database 'CARS_DATABASE', wherein there are the following tables:
Lorries
Vans
Buses
Convertibles
City_cars
Stretch_limos
Rescue_vehicles
Double_decker_buses
First of all, I am going to run the following query to get the list of the tables:
SELECT TableName
FROM
(SELECT TableName
FROM DBC.TablesV
WHERE DatabaseName = 'CARS_DATABASE';
Now, I would like to incorporate it into one query which would look as follows:
Select count(*) from CARS_DATABASE.**TableName**
WHERE TableName = (SELECT TableName
FROM
(SELECT TableName
FROM DBC.TablesV
WHERE DatabaseName = 'CARS_DATABASE') Q1);
I wonder how I can make this dynamic and pass into FROM clause the names of all tables. Essentially, I would like it to select from all those tables dynamically, e.g.
Select count(*) from CARS_DATABASE.Lorries
Select count(*) from CARS_DATABASE.Vans
Select count(*) from CARS_DATABASE.Buses
and so on.
Do I have to write a macro or stored procedure to achieve that?
Many thanks in advance for your suggestions.
Cheers
Andy
Have a derived table (the subquery), where you SELECT and UNION ALL the different vehicle tables. GROUP BY the result.
select vehicle_type, count(*)
from
(
select 'lorries' as vehicle_type from CARS_DATABASE.Lorries
union all
select 'vans' as vehicle_type from CARS_DATABASE.vans
union all
...
select 'Double_decker_buses' as vehicle_type from CARS_DATABASE.Double_decker_buses
) vehicles
GROUP BY vehicle_type
Note: I'd store all vehicles in one common table. If you're stuck with separated tables, you could create a view to UNION ALL the different tables.

Select unmatching rows from two tables grouping by two columns

I have two tables with sales information that have different number of rows and I want to get these rows. An important thing to notice is that records are added to the tables by the key of two columns: sale_type and sale_date.
So I think I should group by these columns after making a Union of the two tables. And filter by count. But my current solution does not work. How should I fetch the unmatching records correctly?
Here is what I've tried:
SELECT * FROM
(SELECT * FROM sales_copy
UNION ALL
SELECT * FROM sales)
GROUP BY sale_type, sale_date
HAVING count(*)!=1;
To select the difference between two tables, I've managed to do this successfully using a full join.
So in your case, you would want something like:
SELECT S.*, SC.*
FROM sales AS S
FULL JOIN sales_copy AS SC ON (S.sale_type = SC.sale_type) AND (S.sale_date =
SC.sale_date
WHERE (S.sale_type IS NULL AND S.sale_date IS NULL) OR (SC.sale_type IS NULL AND
SC.sale_date IS NULL)
The result of this will select all the rows which are in one table only, ignoring the rows which are in both.
See it in action here: SQL Fiddle
You can use both EXCEPT and UNION operator :
SELECT sale_type, sale_date FROM sales EXCEPT SELECT sale_type,sale_date FROM sales_copy
UNION
SELECT sale_type, sale_date FROM sales_copy EXCEPT SELECT sale_type,sale_date FROM sales
It returns rows from sales wich are not in sales_copy and rows from sales_copy wich are not in sales
The same thing can be achieved with a full join by filtering rows wich are matching:
SELECT ISNULL(sales.sale_type, sales_copy.sale_type) AS sale_type
, ISNULL(sales.sale_date, sales_copy.sale_date) AS sale_date
FROM sales
FULL JOIN sales_copy
ON sales.sale_type = sales_copy.sale_type
AND sales.sale_date = sales_copy.sale_date
WHERE sales.sale_type IS NULL
OR sales_copy.sale_type IS NULL

Sum fields from mutiple tables with conditions

I'm working on a quite big project and I need to compute some values through SQL. I have 3 datasets with quite identical fields :
Query1 : txt groupName, int cat, long hoursSubTot1
Query2 : txt groupName, int cat, long hoursSubTot2
Query3 : txt groupName, int cat, long hoursSubTot3
I need to add hoursSubTot1,hoursSubTot2 and hoursSubTot3 like that :
I would like the datas to be agregate as shown in the result table. But I do not manage to agregate the right values in Access, I am out of ideas so any help or advice would be welcome...
Thanks!
If you're not opposed to using multiple queries, here's my thought. First create a query using UNION ALL to combine the three queries. Then you can create a new query to calculate the sums.
SELECT Group, Category, Hours FROM Table1
UNION ALL
SELECT Group, Category, Hours FROM Table2
UNION ALL
SELECT Group, Category, Hours FROM Table3
ANSI SQL answer, may or may not work for Access:
select group, category, sum(hours)
from
(
select group, category, hours from table1
union all
select group, category, hours from table2
union all
select group, category, hours from table3
)
group by group, category

combine SELECTS in ONE VIEW DISPLAY

I need to know of a way to combine multiple SELECT statements in one VIEW? I tried the UNION ALL, but it fails since I am using unique columns to aggregate the GRAND TOTAL.
I am a student this is part of a group project.
I have one table with 4 columns: account, description, short_description, and balance. The COA (chart of accounts) is an excel spreadsheet that is imported.
CREATE VIEW [account_balance_sums]
AS
SELECT SUM(balance) AS total,
SUBSTRING (Account,0,2) AS account_group
FROM COA
GROUP BY account_group
GO
SELECT * FROM [account_balance_sums]
SELECT SUM(total) AS Grand_total
FROM [account_balance_sums]
Assuming that you are trying to create a view that gives account group and total balance with a single extra row for the total across all accounts then this view should help:
CREATE VIEW [account_balance_sums] AS
SELECT SUM(balance) AS total, SUBSTRING (Account,0,2) AS account_group
FROM COA
GROUP BY account_group
UNION ALL
SELECT SUM(balance), 'Grand Total'
FROM account_group
By the way, the sub-string of the first characters of the account name suggests that you have more than one piece of data in a single column. This indicates a data that is not properly normalised, which you should probably address if you want top marks. See wikipedia on normal form
In a UNION'd statement, there must be:
The same number of columns in each SELECT statement
The data types must match at each position in the SELECT statement
Use:
SELECT *
FROM [account_balance_sums]
UNION ALL
SELECT SUM(total),
NULL AS account_group
FROM [account_balance_sums]
UNION ALL should work. basic structure like this
select a,b,c,d
from t1
union all
select a,b,c,e
from t2
so long as d and e are the same data type.
to do the sum, then you wrap this with the aggregation layer - using this structure as an inline view (among other methods)
something like:
select sum( d )
from (
select a,b,c,d
from t1
union all
select a,b,c,e
from t2
)