How can I obtain a transposed UNION of 3 SQL Tables? - sql

How can I obtain a transposed UNION of the TSQL Query Results below
SELECT TOP 1 Column_A FROM table1
SELECT TOP 1 Column_B FROM table2
SELECT TOP 1 Column_C FROM table3
So that the output will be ONE row of 3 columns with a single value per each:
[Column_A] [Column_B] [Column_C]

Like this:
Select
(SELECT TOP 1 Column_A FROM table1) as 'Column_A',
(SELECT TOP 1 Column_B FROM table2) as 'Column_B',
(SELECT TOP 1 Column_C FROM table3) as 'Column_C'

Related

Ger rows with 2 specifical occurrences

Column_A
Column_B
1
X
1
Z
2
X
2
Y
3
Y
4
X
4
Y
4
Z
5
Y
I want get all distinct values of Column A that has a row with Column B equal to X and other row with Column B equal to 'Y'
The result will be like this:
Column_A
1
4
I tried in this way:
SELECT DISTINCT COLUMN_A
FROM TABLE
INNER JOIN (
SELECT DISTINCT COLUMN_A
FROM TABLE
WHERE COLUMN_B = 'X') SUBTABLE
ON TABLE.COLUMN_A = SUBTABLE.COLUMN_A
WHERE TABLE.COLUMN_B = 'Y';
I think that this solution works but isn't optimum
Thanks a have a nice day
You can apply a simple aggregation by:
filtering only Column_B values you're interested in
aggregating for distinct values of Column_B
checking the amount of distinct values equals 2
SELECT Column_A
FROM tab
WHERE Column_B IN ('X', 'Y')
GROUP BY Column_A
HAVING COUNT(DISTINCT Column_B) = 2
or you can use the INTERSECT operator between:
the records having Column_B = 'X'
the records having Column_B = 'Y'
SELECT DISTINCT Column_A FROM tab WHERE Column_B = 'X'
INTERSECT
SELECT DISTINCT Column_A FROM tab WHERE Column_B = 'Y'
Check the demo here.

Get unique rows from two tables, but keep duplicates from the same table

I want to split a table into two tables (or more, but let's say two).
table_original
id column1 column2
1 1 2
2 1 3
3 1 4
4 1 4
5 1 5
We can also assume that id is a unique identifier. Now I split this table into two, by using a CREATE TABLE table1 AS SELECT * FROM table_original WHERE column2 <= 4 and CREATE TABLE table2 AS SELECT * FROM table_original WHERE column2 >= 4. Now I have these two tables:
table1
id column1 column2
1 1 2
2 1 3
3 1 4
4 1 4
table2
id column1 column2
3 1 4
4 1 4
5 1 5
How to get the same results from those two tables that I can get from the original table? If I run a query SELECT * FROM table1 UNION SELECT * FROM table2 it will be the same as SELECT * FROM table_original because of the unique id value, however if I run a query SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2 it returns:
column1, column2
1 2
1 3
1 4
1 5
which is not the same as SELECT column1, column2 FROM table_original, which returns:
column1, column2
1 2
1 3
1 4
1 4
1 5
Duplicates from the same table are removed. However, if I wanted to let's say do a count on duplicates, the results will be different, which is bad. So is there a way to do a UNION type operation but keep duplicates that are found in the same table?
not sure what are you trying to achieve but you need to use union all:
SELECT column1, column2 FROM table1
UNION ALL
SELECT column1, column2 FROM table2
union all keeps the duplicates
The UNION on whole rows in your solution will be painfully expensive for big tables (and wide rows). And it fails outright with any column type that doesn't support the equality operator (like json). See:
UNION ALL on JSON data type
This query is substantially faster, making use of the unique index on table1(id). (Create that index if you don't have it!)
SELECT column1, column2
FROM table1 -- bigger table first to micro-optimize some more
UNION ALL
SELECT column1, column2
FROM table2 t2
WHERE NOT EXISTS (SELECT FROM table1 WHERE id = t2.id)
See:
Select rows which are not present in other table
About UNION ALL (as opposed to just UNION):
Is order preserved after UNION in PostgreSQL?
Combining 3 SELECT statements to output 1 table
The question remains: Why keeps completely duplicate rows in multiple tables?
I've figured out the answer.
To keep the duplicates found in the same table, but eliminate everything else, I used a query SELECT column1, column2 FROM (SELECT * FROM table1 UNION SELECT * FROM table2) AS t;
This way the UNION uses the unique id values to eliminate real duplicates, and after that I just filter the result to get the columns I need.

Select a record having null if the id has only one record and select not null value when the id has more than one record

I want to get a record having null if the id has only one record and select not null value when the id has more than one record
Below is example sample.
Id Field1 Field2
1 Null 34
1 Yes 52
2 Null 56
3 No 46
and output
Id Field1 Field2
1 Yes 52
2 Null 56
3 No 46
How it can be done using sql query?
Use the below query for 2008+ versions of sql server.
;with cte_1
As
( select *, count(1) over (partition by id order by id) Cnt
From YourTable)
Select Id,Field1,Field2
From Cte_1
Where Field1 is null and Cnt=1
UNION
Select Id,Field1,Field2
From YourTable
Where field1 is not null
Sample output :
Use the below query for 2005 version.
SELECT t.Id,Field1,Field2
FROM #T t
JOIN (select ID, count(ID) CntId
From #t
GROUP BY ID
HAVING COUNT(ID)=1)t1 on t.ID=t1.ID
WHERE t.Field1 is null
UNION
SELECT Id,Field1,Field2
FROM #T
WHERE Field1 is NOT NULL
ORDER BY ID
Sample output :
It sounds like you can only have one or two rows per group and one of them must have the null. Using those assumptions you can get away with a simple query.
select
Id,
min(Field1) as Field1,
coalesce(min(case when Field1 is not null then Field2 end), min(Field2)) as Field2
from T
group by Id
It also makes a minor assumption that Field2 isn't nullable. Actually it's a little more subtle than that but there's a workaround if you need it.
A solution using exists and a subquery is another option:
select * from T t1
where Field is not null or not exists (
select 1 from T t2
where t2.Id = t1.Id and t2.Field is not null
)
Use this code:
Select Distinct ID,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field1,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field2
From Table1 as Tbl1
Result:
ID Field1 Field2
----------- ---------- -----------
1 Yes 52
2 NULL 56
3 No 46
(3 row(s) affected)
Also below code get same result:
Select Distinct ID,
(Select Top 1 Field1 From Table1 Where ID=Tbl1.ID Order By Field1 Desc) as Field1,
(Select Top 1 Field2 From Table1 Where ID=Tbl1.ID Order BY field1 Desc) as Field2
From Table1 as Tbl1

require to form a sql query

I was working on preparing a query where I was stuck.
Consider tables below:
table1
id key col1
-- --- -----
1 1 abc
2 2 d
3 3 s
4 4 xyz
table2
id col1 foreignkey
-- ---- ----------
1 12 1
2 13 1
3 14 1
4 12 2
5 13 2
Now what I need is to select only those records from table1 for which the corresponding entries in table2 does not have say col1 value as 12.
So the challenge is after applying join even though it will skip for value 1 corresponding to col1 equal to 12 it still has another multiple rows whose values are say 13, 14 for which also they have same foreignkey. Now what I want is if there is a single row having value 12 then it should not pick that id at all from table1.
How can I form a query with this?
The output which i need is say from above table structure i want to get those records from table1 for which col1 value from table2 does not have value as 14.
so my query should return me only row 2 from table1 and not row 1.
Another way of doing that. The first two queries are just for making the sample data.
;WITH t1(id ,[key] ,col1) AS
(
SELECT 1 , 1 , 'abc' UNION ALL
SELECT 2 , 2 , 'd' UNION ALL
SELECT 3 , 3 , 's' UNION ALL
SELECT 4 , 4 , 'xyz'
)
,t2(id ,col1, foreignkey) AS
(
SELECT 1 , 12 , 1 UNION ALL
SELECT 2 , 13 , 1 UNION ALL
SELECT 3 , 14 , 1 UNION ALL
SELECT 4 ,12 , 2 UNION ALL
SELECT 5 ,13 , 2
)
SELECT id, [key], col1
FROM t1
WHERE id NOT IN (SELECT t2.Id
FROM t2
INNER JOIN t1 ON t1.Id = t2.foreignkey
WHERE t2.col1 = 14)
This is a typical case for NOT EXISTS:
SELECT id, [key], col1
FROM table1 t1
WHERE NOT EXISTS (SELECT 1
FROM table2 t2
WHERE t2.foreignkey = t1.id AND t2.col1 = 14)
The above query will not select a row from table1 if there is a single correlated row in table2 having col1 = 14.
Output:
id key col1
-------------
2 2 d
3 3 s
4 4 xyz
If you want to return records that, in addition to the criterion set above, also have correlated records in table2, then you can use the following query:
SELECT t1.id, MAX(t1.[key]) AS [key], MAX(t1.col1) AS col1
FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.foreignkey
GROUP BY t1.id
HAVING COUNT(CASE WHEN t2.col1 = 14 THEN 1 END) = 0
Output:
id key col1
-------------
2 2 d
You can also achieve the same result with the second query using a combination of EXISTS and NOT EXISTS:
SELECT id, [key], col1
FROM table1 t1
WHERE EXISTS (SELECT 1
FROM table2 t2
WHERE t2.foreignkey = t1.id)
AND
NOT EXISTS (SELECT 1
FROM table2 t3
WHERE t3.foreignkey = t1.id AND t3.col1 = 14)
select t1.id,t1.key,
(select ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col1 DESC) AS Row,* into
#Temp from table1)
from table1 t1
inner join table2 t2 on t1.id=t2.foreignkey
where t2.col1=(select col1 from #temp where row>1)

How to get the records from multiple tables?

Hi I am new to the Database, and i am trying to get the records from the multiple tables, but depending upon there selection following is my tables
Table1
Column1 Column2
1 10
2 25
3 23
4 15
5 7
Table2
Column1 Column2
2 15
3 13
5 17
Table3
Column1 Column2
2 45
Resultant Table should have records like
Column1 Column2
1 10
2 45
3 13
4 15
5 17
i am trying but not got the output yet. Any help or the direction to work out this output will be great help.
UPDATE
What i want is get the all rows from table1 then if table2 contains the matching records then it will remove the matching records form the resultset and add the table2 matching records and then same is repeated by table3.
SELECT t1.column1, COALESCE(t3.column2,t2.column2,t1.column2)
FROM t1
LEFT JOIN t2 on t1.column1=t2.column1
LEFT JOIN t3 on t1.column1=t3.column1
Please use the Below Code and Try
select * from table1 where column1 not in ( select column1 from table2 union select column1 from table3)
union
select * from table2 where column1 not in (select column1 from table3)
union
select * from table3
select x.col1,max(x.col2) from (
select * from #t1
union
select * from #t2
union
select * from #t3
)x
group by x.col1
see it in action