I need to combine three tables and find the total count for fruit after combining the three tables using SQL. The name of the fruit columns in the three tables are pr16pnk.fruit, pr16puf.fruit, and pr16yag.fruit. I have successfully found the results when the tables are separated, but I am having trouble combining the results. Listed below is the code that I used. I also need help putting it in descending order.
SELECT pr16pnk.fruit, COUNT(*)
FROM pr16pnk
GROUP BY pr16pnk.fruit
UNION ALL
SELECT pr16puf.fruit, COUNT(*)
FROM pr16puf
GROUP BY pr16puf.fruit
UNION ALL
SELECT pr16yag.fruit, COUNT(*)
FROM pr16yag
GROUP BY pr16yag.fruit
Use aggregators and ORDER BY, query is as simple as below
SELECT sum(A.fruit ,B.fruit, C.fruit)
FROM pr16pnk A
pr16puf B'
pr16yag C
ORDER BY fruit desc;
Just use a subquery:
SELECT fruit, SUM(cnt)
FROM ((SELECT pr16pnk.fruit, COUNT(*) as cnt
FROM pr16pnk
GROUP BY pr16pnk.fruit
) UNION ALL
SELECT pr16puf.fruit, COUNT(*) as cnt
FROM pr16puf
GROUP BY pr16puf.fruit
) UNION ALL
(SELECT pr16yag.fruit, COUNT(*) as cnt
FROM pr16yag
GROUP BY pr16yag.fruit
)
) f
GROUP BY fruit
Try this,
select f.fruit, count(*) from
(
SELECT pr16pnk.fruit from pr16pnk
union
SELECT pr16puf.fruit from pr16puf
union
SELECT pr16yag.fruit from pr16yag
) f
group by f.fruit
order by f.fruit desc
SELECT COUNT(id)
FROM table1
UNION
SELECT COUNT(id)
FROM table2
UNION
SELECT COUNT(id)
FROM table3
Result is
247811
58599
76
But actually
table1 has 247811 rows
table2 has 76 rows
table3 has 58599 rows
The union operator makes no gaurantees about the order. If you want to order the results in a particular way, you'd have to do so explicitly, with an order by clause. Note also that union removes duplicates, so you'd better use union all. E.g.:
SELECT cnt
FROM (SELECT 't1', COUNT(id) FROM table1
UNION ALL
SELECT 't2', COUNT(id) FROM table2
UNION ALL
SELECT 't3', COUNT(id) FROM table3) t
ORDER BY 1 ASC
if your problem depends on order by please order by your select after union, if you have a problem with count?(in your example there is a different count 79 and 76) it depends on that you use count(id) it is not same is count(*), count(id) ignores every null in Id column, count(*) it is count of your table rows
I'm having a hard time summing up a column on two tables. The scenario is something like this (refer to the image below)
Table 1 may have a lot of rows per Date. But Table 2 may only consists of two rows of data per Date. What I wanted to do is to sum up all Item/Price (Table1) according to their Date and ADD them with another SUM of Item/Price of Table2. The category of SUM is by Date.
I tried any joins statement (left, right or inner) but it does not produce the result that I am expecting to. My expected result is the Result table. But on my query, it produces a very high value.
Thanks.
Use a UNION clause like this:
WITH t(d, p) AS (
SELECT [Date], Price FROM Table1
UNION ALL
SELECT [Date], Price FROM Table2
)
SELECT d, SUM(p) FROM t GROUP BY d
You can do this with UNION ALL in either a subquery or a cte, cte shown here:
;WITH cte AS (SELECT [Date], Price
FROM Table1
UNION ALL
SELECT [Date], Price
FROM Table2
)
SELECT [Date], SUM(Price) AS Total_Price
FROM cte
GROUP BY [Date]
Demo: SQL Fiddle
Try This,
with cte (C_Date,C_Price)
as
(
SELECT date,SUM(price) FROM table_1
group by date
union
SELECT date,SUM(price) FROM table_2
group by date
)
select c_date,SUM(c_price) from cte
group by C_Date
Try this
Select t.date,P1+P2
from(
Select Date,sum(Price) P1
from table1 t
group by Date
) t
left join
(
Select Date,sum(Price) P2
from table t2
group by date
) t1 on t.date = t1.date
group by date
I'm trying to do multiple select from diff tables and just have a result in one column.
SELECT COUNT(*) FROM tb1 union
SELECT COUNT(*) FROM tb2 union
SELECT COUNT(*) FROM tb3;
output should be like:
593643
18103600
0
Problem with this is that the result is being arranged on desc order.
Like below:
0
593643
18103600
I would want the result to be as I put the select statement.
Please advise. Btw, I'm using teradata.
Thank you.
SQL result sets are inherently unordered, unless you explicitly specify an order by clause. You can do this with a subquery:
select cnt
from ((SELECT COUNT(*) as cnt, 1 as ord FROM tb1)
union all
(SELECT COUNT(*), 2 FROM tb2)
union all
(SELECT COUNT(*), 3 FROM tb3)
) t
order by ord
If you want specific order, add ORDER BY clause. It would also be good to use UNION ALL so you always get 3 rows, even with duplicate results (two tables having the same number of rows):
SELECT 'tbl1' AS tablename, COUNT(*) AS cnt, 1 AS ord FROM tb1 UNION ALL
SELECT 'tbl2', COUNT(*), 2 FROM tb2 UNION ALL
SELECT 'tbl3', COUNT(*), 3 FROM tb3
ORDER BY ord ;
How can one programmatically sort a union query when pulling data from two tables? For example,
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
Throws an exception
Note: this is being attempted on MS Access Jet database engine
Sometimes you need to have the ORDER BY in each of the sections that need to be combined with UNION.
In this case
SELECT * FROM
(
SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2
SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
ORDER BY field1
I think this does a good job of explaining.
The following is a UNION query that uses an ORDER BY clause:
select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;
Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.
In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the
result set.
Taken from here: http://www.techonthenet.com/sql/union.php
Using a concrete example:
SELECT name FROM Folders ORDER BY name
UNION
SELECT name FROM Files ORDER BY name
Files:
name
=============================
RTS.exe
thiny1.etl
thing2.elt
f.txt
tcpdump_trial_license (1).zip
Folders:
name
============================
Contacts
Desktop
Downloads
Links
Favorites
My Documents
Desired Output: (results of first select first, i.e. folders first)
Contacts
Desktop
Downloads
Favorites
Links
My Documents
f.txt
RTMS.exe
tcpdump_trial_license (1).zip
thiny1.etl
thing2.elt
SQL to achieve the desired results:
SELECT name
FROM (
SELECT 1 AS rank, name FROM Folders
UNION
SELECT 2 AS rank, name FROM Files) dt
ORDER BY rank, name
Here's an example from Northwind 2007:
SELECT [Product ID], [Order Date], [Company Name], [Transaction], [Quantity]
FROM [Product Orders]
UNION SELECT [Product ID], [Creation Date], [Company Name], [Transaction], [Quantity]
FROM [Product Purchases]
ORDER BY [Order Date] DESC;
The ORDER BY clause just needs to be the last statement, after you've done all your unioning. You can union several sets together, then put an ORDER BY clause after the last set.
(SELECT table1.field1 FROM table1
UNION
SELECT table2.field1 FROM table2) ORDER BY field1
Work? Remember think sets. Get the set you want using a union and then perform your operations on it.
SELECT table1Column1 as col1,table1Column2 as col2
FROM table1
UNION
( SELECT table2Column1 as col1, table1Column2 as col2
FROM table2
)
ORDER BY col1 ASC
SELECT field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) AS TBL
ORDER BY TBL.field1
(use ALIAS)
This is the stupidest thing I've ever seen, but it works, and you can't argue with results.
SELECT *
FROM (
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) derivedTable
The interior of the derived table will not execute on its own, but as a derived table works perfectly fine. I've tried this on SS 2000, SS 2005, SS 2008 R2, and all three work.
This is how it is done
select * from
(select top 100 percent pointx, pointy from point
where pointtype = 1
order by pointy) A
union all
select * from
(select top 100 percent pointx, pointy from point
where pointtype = 2
order by pointy desc) B
Browsing this comment section I came accross two different patterns answering the question. Sadly for SQL 2012, the second pattern doesn't work, so here's my "work around"
Order By on a Common Column
This is the easiest case you can encounter. Like many user pointed out, all you really need to do is add an Order By at the end of the query
SELECT a FROM table1
UNION
SELECT a FROM table2
ORDER BY field1
or
SELECT a FROM table1 ORDER BY field1
UNION
SELECT a FROM table2 ORDER BY field1
Order By on Different Columns
Here's where it actually gets tricky. Using SQL 2012, I tried the top post and it doesn't work.
SELECT * FROM
(
SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2
Following the recommandation in the comment I tried this
SELECT * FROM
(
SELECT TOP 100 PERCENT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT TOP 100 PERCENT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2
This code did compile but the DUMMY_ALIAS1 and DUMMY_ALIAS2 override the Order By established in the Select statement which makes this unusable.
The only solution that I could think of, that worked for me was not using a union and instead making the queries run individually and then dealing with them. So basically, not using a Union when you want to Order By
By using order separately each subset gets order, but not the whole set, which is what you would want uniting two tables.
You should use something like this to have one ordered set:
SELECT TOP (100) PERCENT field1, field2, field3, field4, field5 FROM
(SELECT table1.field1, table1.field2, table1.field3, table1.field4, table1.field5 FROM table1
UNION ALL
SELECT table2.field1, table2.field2, table2.field3, table2.field4, table2.field5 FROM table2)
AS unitedTables ORDER BY field5 DESC
The second table cannot include the table name in the ORDER BY clause.
So...
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1
Does not throw an exception
If necessary to keep the inner sorting:
SELECT 1 as type, field1 FROM table1
UNION
SELECT 2 as type, field1 FROM table2
ORDER BY type, field1
(SELECT FIELD1 AS NEWFIELD FROM TABLE1 ORDER BY FIELD1)
UNION
(SELECT FIELD2 FROM TABLE2 ORDER BY FIELD2)
UNION
(SELECT FIELD3 FROM TABLE3 ORDER BY FIELD3) ORDER BY NEWFIELD
Try this. It worked for me.
For Sql Server 2014/2012/Others(Not Checked) :
SELECT * FROM
(
SELECT table1.field1 FROM table1 ORDER BY table1.field1
)
as DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT table2.field1 FROM table2 ORDER BY table2.field1
)
as DUMMY_ALIAS2