Show each table after the other in UNION SQL - sql-server

I want to show two result sets in one result set, using UNION
The problem is, I want it to show all of the first table's records, and then go to the next one
But since SQL Server automatically orders the results by the first column, the final results get ordered by ID column, which both tables have
Both tables have a column with the ID of 1, 2, 3 and so on, and therefore the result of the UNION is like this:
[table 1].[record 1]
[table 2].[record 1]
[table 1].[record 2]
[table 2].[record 2]
I want it to show like this:
[table 1].[record 1]
[table 1].[record 2]
[table 1].[record 3]
[table 2].[record 1]
[table 2].[record 2]
[table 2].[record 3]

Add an "ordering column" e.g.
select 0 Orderb, T1.*
from Table1 T1
union all
select 1 Orderb, T2.*
from Table2 T2
order by OrderBy, id; -- whatever columns you wish to order by

Related

Sum data and merge results by updating table

I have a table with the following data:
Table1
UniqueKey
Text A
Text B
Value 1
Value 2
Key1
ABC
ABC
2
3
Key2
DEF
GHI
3
4
Key3
STE
GGE
5
5
Key2
DEF
GHI
3
4
Key2
DEF
GHI
5
7
Key1
ABC
ABC
3
7
Using the key UniqueKey I want to add the values in the columns Value 1 and Values 2 so that each Unique Key exists only once in my table.
The Table1 should then look like this:
UniqueKey
Text A
Text B
Value 1
Value 2
Key1
ABC
ABC
5
10
Key2
DEF
GHI
11
15
Key3
STE
GGE
5
5
I have already made the following considerations. I can use the group by and sum command to add the columns as desired.
I have trouble saving these changes in the table and deleting the redundant columns. So far I have only used the merge command on two different tables.
SELECT UniqueKey, SUM(Value1) Value1, SUM(Value2) Value2
FROM Table1
GROUP BY UniqueKey
Has anyone an idea?
You can create a new table with the current query
SELECT [UniqueKey], [Text A], [Text B], SUM([Value 1]) AS Value1, SUM([Value 2]) AS Value2
INTO Table2
FROM Table1
GROUP BY [UniqueKey], [Text A], [Text B]
drop the original source
DROP TABLE Table1
rename new one to the original
sp_rename 'Table2', 'Table1'
and add a primary key on UniqueKey column to enforce uniqueness as the last step
ALTER TABLE Table1 ADD PRIMARY KEY (UniqueKey);
You will need to group by the columns the other 2 columns Text A and Text B.
SELECT UniqueKey, [Text A], [Text B], SUM([Value 1]) AS Val1, SUM([Value 2]) AS Val2
FROM Table1
GROUP BY UniqueKey, [Text A], [Text B]
If you want to get this data into Table1, you can save the result of the query above in a temp table, delete the data in Table1, then re-insert the data from the temp table into Table1.
-- Check if you have a temp table #Table1, if so drop it
IF OBJECT_ID('tempdb..#Table1') IS NOT NULL
BEGIN
DROP TABLE #Table1
END
GO
-- Save the data into temp table #Table1
SELECT UniqueKey, [Text A], [Text B], SUM([Value 1]) AS Val1, SUM([Value 2]) AS Val2 INTO #Table1
FROM Table1
GROUP BY UniqueKey, [Text A], [Text B]
GO
-- Delete the data in Table1
DELETE FROM Table1
GO
-- Re-insert the data from the temp table #Table1 into Table1
INSERT INTO Table1 (UniqueKey, [Text A], [Text B], [Value 1], [Value 2])
SELECT UniqueKey, [Text A], [Text B], [Value 1], [Value 2]
FROM #Table1
GO

Update one column based on three other column which have same value in another table

I have two tables that have 3 fields with the same value and one relation field in the table1. Let me explain.
table1
------
id
column1
column2
column3
table2_id
table2
-------
id
column1
column2
column3
In table2; column1, column2 and column3 can have same value for different ids. For example:
table2
-------
1, 2, 3, 4
2, 2, 3, 4
3, 4, 5, 6
Ass you can see, only ids are different for the first two records. The others are the same. Also in table1:
table1
-------
1, 2, 3, 4, null
2, 4, 5, 6, null
I want to update table1's table2_id field(which are null in example) for only records in table1 that have one specific record for column1, column2, column3.
So I expect that:
table1
------
1, 2, 3, 4, null
2, 4, 5, 6, 3
first record will be still null because 2 different ids can be linked there. But for the second record, table2_id can only be '3'
How can I write the query for this update process?
You can solve it with an additional table or CTE to identify duplicate or genuine records. A GROUP BY or a join can be used to check the duplicates.
Please note that you also need to check for nulls in equations if the columns are nullable.
with GenuineData as (
select
min(t2.Id) id
from
Table2 t2
group by
t2.Column1,
t2.Column2,
t2.Column3
having
count(*) = 1
)
update t1 set
t1.Table2Id = t2.Id
from
Table1 t1
join Table2 t2 on t2.Column1 = t1.Column1 and t2.Column2 = t1.Column2 and t2.Column3 = t1.Column3
join GenuineData gd on gd.id = t2.Id
If the columns are nullable, you can use ISNULL() in the equations, or for better performance, an extended criteria for joining Table2 as below:
join Table2 t2 on
(t2.Column1 = t1.Column1 or (t1.Column1 is null and t2.Column1 is null))
and (t2.Column2 = t1.Column2 or (t1.Column2 is null and t2.Column2 is null))
and (t2.Column3 = t1.Column3 or (t1.Column3 is null and t2.Column3 is null))

Selecting Columns A values if no like a value in column B in SQL Server

I have Table1
And I am trying to remove every identical Column A value if one of it's row has "ZX" anywhere in Column B. So if I did it right, it will look like Table2
I did the following:
Select
Column A,
Column B
From
Table1
Where
Column B not like '%ZX%'
However, it only removes rows with ZX and not every identical Column A values and returns this Table instead
I will really appreciate any help on this! Thank you in advance :)
You can use NOT IN
SELECT
ColumnA
, ColumnB
FROM table1
WHERE ColumnA NOT IN (SELECT ColumnA FROM table1 WHERE ColumnB like '%ZX%')
I like not exists for this purpose:
Select t1.*
From Table1 T1
where not exists (select 1 from table1 tt1 where tt1.a = t1.a and tt1.b like '%ZX%');
This can take advantage of an index on table1(a, b).
Use :NOT EXISTS and that should do it:
Select
[Column A],
[Column B]
From Table1 T1
where
NOT EXISTS (
SELECT 1 FROM TABLE1 T2
WHERE T2.[Column B] like '%ZX%'
AND T2.[column a] = t1.[column a]
)

How to pull the duplicate record in SQL

I have some records that looks like this.
I want to pull out as the following.
Is this possible?
I can only pull out the duplicate values but can't get that I want.
SELECT [COLUMN A] , COUNT([COLUMN A]) FROM [MYTABLE] GROUP BY [COLUMN A] HAVING COUNT([COLUMN A]) >1 ORDER BY [COLUMN A]
Anyone please help me.
Thanks.
You can use the following query to get the desired result:
SELECT
ColumnA
, MAX(ColumnB) ColumnB
, MIN(ColumnC) ColumnC
, MAX(ColumnC) ColumnD
FROM MYTABLE
GROUP BY ColumnA
ORDER BY ColumnA;
Try in the 'Count()' sentence add the id or *
i.e.:
SELECT [COLUMN A] , COUNT(*) FROM [MYTABLE] GROUP BY [COLUMN A] HAVING COUNT(*) >1 ORDER BY [COLUMN A]
or
SELECT [COLUMN A] , COUNT(´id_col_A´) FROM [MYTABLE] GROUP BY [COLUMN A] HAVING COUNT(´id_col_A´) >1 ORDER BY [COLUMN A]

sql server cursor comparison

i have 2 cursor in which cursor 1 has select * from table 1 and cursor 2 has select * from table 2. I need to compare 2 cursors and if the fetched row in the cursor 1 is not equal to fetched row of cursor 2, then i wants to delete that fetched row from table 2. Please help me how to do this?
You can use EXCEPT to identify the changed rows.
;WITH DirtyRows AS
(
SELECT * FROM [Table 1]
EXCEPT
SELECT * FROM [Table 2]
)
DELETE [Table 2]
WHERE EXISTS
(
SELECT * FROM DirtyRows
WHERE DirtyRows.Id = [Table 2].Id
)
Why would you want to do that with cursors?, If I understood you correctly, you can just do:
DELETE B
FROM table1 A
INNER JOIN table2 B
ON A.Id = B.Id
WHERE A.column1 <> B.column1 OR A.column2 <> B.Column2 ....
Or something like that.

Resources