how to combine the two queries sql? - sql

Good day.
I have two sql query:
First:
SELECT name FROM
TableOne
WHERE city='3452' AND firm='49581' AND service='2'
Group by name
Second:
SELECT name FROM
TableTwo
WHERE city='3452' AND firm='49581' AND service='2'
Group by name
Tell me please how to combine the two queries sql and select all name (with group by name) from two tables ?

You can use UNION ALL http://sqltutorials.blogspot.com/2007/06/sql-union-all.html
SELECT name
FROM (
SELECT name
FROM TableOne
WHERE city='3452' AND firm='49581' AND service='2'
UNION ALL
SELECT name
FROM TableTwo
WHERE city='3452' AND firm='49581' AND service='2' ) x
GROUP BY name

Just use UNION operator between two queries. According to answer in this similar question:
You may be looking at using a UNION in you query:
Select * from a UNION Select * from b Note:
It is better practice to
qualify your column names instead of using the * reference. This would
also make the query still useful if your two tables underwent schema
changes but you still wanted to pull back all the data the two tables
had in common.
Union will rule out same objects. To avoid that you can use UNION ALL instead.

Well, "combine" can mean a lot of things, but I'm guessing you want something like this:
SELECT name
FROM (
SELECT name, city, firm, service FROM TableOne
UNION ALL
SELECT name, city, firm, service FROM TableTwo
) Q
WHERE city='3452' AND firm='49581' AND service='2'
GROUP BY name
There is no need to use UNION (without ALL), since GROUP BY will remove the duplicates anyway.
BTW, are all these fields used in the WHERE clause really strings? If not, you'd want to remove single quotes as appropriate. It's a bit suspicious that you are using string literals that contain only numbers.

I believe this syntax is a little simpler and thus easier to maintain. The comma in line two does a join.
SELECT name FROM
TableOne, TableTwo
WHERE city='3452' AND firm='49581' AND service='2'
Group by name

Related

Query for selecting same or similar data from different tables

I have doc_no, I need to find out its type. So I need to select a query from the table.
SELECT o.type_id
FROM operation_out o
WHERE o.doc_no = 17025337;
But what to do, if I have 3 different tables
operation_out, operation_in, operation_reverse
and given doc_no can be in any of the given tables.
I have already tried union:
SELECT transfer_type_id
FROM (SELECT doc_no, mt_o.type_id
FROM mt_operation_out mt_o
UNION ALL
SELECT doc_no, mt_in.type_id
FROM mt_operation_in mt_in
UNION ALL
SELECT doc_no, mt_r.type_id
FROM mt_operation_reverse mt_r)
WHERE doc_no = 17025337;
Is there another alternative way of writing this? Is there any syntax in SQL for this kind of task?
Thank you all for your recommendations. In the end, I created a view based on the UNION ALL, and I'm going to use it wherever needed.

Select query group by alias

I have this query:
SELECT * FROM TABLE1 WHERE AREA_CODE IN ('929', '718', '347', '646') GROUP BY AREA_CODE
Is it possible to get only one record row with name 'NEW_YORK_AREA' that includes all these four area codes? To be more clear, let's say you have 4 records in the table for each area code listed above but you want to get only one result(row) with alias 'NEW_YOUR_AREA'. I hope it is clear, let me know if you have any questions, I will edit the question. Thank you all and have a great day.
UPDATE: requirements have changed and it is no longer needed. Thank you all for your help! :)
DB2 supports listagg(). So:
SELECT 'NEW_YORK_AREA' as cityname,
LISTAGG(AREA_CODE, ',') WITHIN GROUP (ORDER BY AREA_CODE) as areacodes
FROM TABLE1
WHERE AREA_CODE IN ('212', '929', '718', '347', '646') ;
I helpfully added 212, the most famous NYC area code ;)
If you have duplicates, then you need to use a subquery to remove them before aggregating.
Logically, what you want to do is group everything into the same category. You could do this by explicitly grouping all rows by a single value:
select 'NEW_YORK_AREA',
--whatever functions you need to aggregate the data here.
count(var1),
max(var2)
from table1
where area_code in ('929', '718', '347', '646')
group by 1
However, if the only functions that refer to the data in the table are aggregate functions, DB2 lets you omit the group by, and it will automatically group everything into a single row. The following is equivalent to the above query:
select 'NEW_YORK_AREA',
count(var1),
max(var2)
from table1
where area_code in ('929', '718', '347', '646')
What about creating a AREA_CODE_GROUP table
AREA_GROUP,AREA_CODE
'NEW_YORK_AREA','929'
'NEW_YORK_AREA','718'
'NEW_YORK_AREA','347'
'NEW_YORK_AREA','646'
that you can join:
SELECT t.* FROM TABLE1 "t"
INNER JOIN AREA_CODE_GROUP "g"
ON t.AREA_CODE = g.AREA_CODE
WHERE AREA_GROUP = 'NEW_YORK_AREA'

getting unique results without using group by

For some reason, I am not able to use GROUP BY but I can use DISTINCT like this:
SELECT DISTINCT(name), id, email from myTable
However above query lists people with same name also because I am selecting more than one columns whereas I want to select only unique names. Is there someway to get unique names without using GROUP BY ?
Although using GROUP BY is the most direct way, you can do other things if it is prohibited. For example, you can use NOT EXISTS with a subquery, like this:
SELECT name, id, email
FROM myTable t
WHERE NOT EXISTS (SELECT * FROM myTable tt WHERE tt.name=t.name AND tt.id < t.id)
This query uses NOT EXISTS to eliminate rows with the same name and IDs higher than the one selected. Note that since this query must pick a single user per name, it may eliminate some users based on their ID, which is a rather arbitrary criterion.

Use distinct keyword with two tables

I want to take unique values using DISTINCT keyword. I have two more tables.
Table Names:
(T1)Cand_details
Locationofwork
(T2)requirement_details
Locationofposting
I want to select these two table values by using keyword distinct. Is this possible?
select LocationOfWork
from cand_details
union
select Locationofposting
from requirement_details;
A UNION operator serves to combine data from multiple SELECT statements.
In this case, without the ALL keyword (UNION ALL), the UNION operator includes a DISTINCT function which will give you the unique locations across both tables.
Something like this?
SELECT DISTINCT Locationofwork, Locationofposting FROM Cand_details, Locationofposting
You should relate both tables with common fields if they have.
Select Locationofwork as "LOC"
From Cand_details
UNION Select Locationofposting as "LOC"
FROM requirement_details
Yes this is easily possible. You can encapsulate as many feilds as you like in the distinct ( ) clause.

Why shouldn’t you use DISTINCT when you could use GROUP BY?

According to tips from MySQL performance wiki:
Don't use DISTINCT when you have or could use GROUP BY.
Can somebody post example of queries where GROUP BY can be used instead of DISTINCT?
If you know that two columns from your result are always directly related then it's slower to do this:
SELECT DISTINCT CustomerId, CustomerName FROM (...)
than this:
SELECT CustomerId, CustomerName FROM (...) GROUP BY CustomerId
because in the second case it only has to compare the id, but in the first case it has to compare both fields. This is a MySQL specific trick. It won't work with other databases.
SELECT Code
FROM YourTable
GROUP BY Code
vs
SELECT DISTINCT Code
FROM YourTable
The basic rule : Put all the columns from the SELECT clause into the GROUP BY clause
so
SELECT DISTINCT a,b,c FROM D
becomes
SELECT a,b,c FROM D GROUP BY a,b,c
Example.
Relation customer(ssnum,name, zipcode, address) PK(ssnum). ssnum is social security number.
SQL:
Select DISTINCT ssnum from customer where zipcode=1234 group by name
This SQL statement returns unique records for those customer's that have zipcode 1234. At the end results are grouped by name.
Here DISTINCT is no not necessary. because you are selecting ssnum which is already unique because ssnun is primary key. two person can not have same ssnum.
In this case Select ssnum from customer where zipcode=1234 group by name will give better performance than "... DISTINCT.......".
DISTINCT is an expensive operation in a DBMS.