SQL, Hive select columns with same values and create new table - sql

I have one table with two columns - Search & Affiliate but some of the values duplicated between both.
Ex: Search 123, 345, 567, 768, 008
Affiliate 425, 345, 986, 008
I want to take the ones present in both (008, 345) + all the other ones in Affiliate and create a separate table, called unique affiliate. The remaining ones in Search is also what I want to convert into another separate table called unique search.
I can create two tables separately, join common values and create a table but how do I include the rest as well with the join? Or maybe pick common values from both and create a new table but then again, what about the rest of the values in each field?

All the affiliates can be found by a simple select distinct from the Affiliate column.
The search can be found by selecting all the Search items that are NOT in the list of Search items that occur in the Affiliate column.
To get the Search items that occur in the affiliate column use an inner join sub query to select them.
Then do a SELECT on the Search column where the items are not in the list generated by the sub query
--INSERT INTO your new affiliates_table
SELECT DISTINCT Affiliate
FROM tbl_SearchAffiliate
WHERE ISNULL(Affiliate,'') <> ''
--INSERT INTO your new search_table
SELECT DISTINCT Search
FROM tbl_SearchAffiliate
WHERE Search NOT IN
( --select the search values that occur in the affilliates column
SELECT x.Search
FROM tbl_SearchAffiliate x
INNER JOIN tbl_SearchAffiliate y ON x.Search = y.Affiliate
)
AND ISNULL(Search,'') <> ''
/********************
below is the data I assumed from your question
CREATE TABLE [dbo].[tbl_SearchAffiliate](
[Search] [nvarchar](50) NULL,
[Affiliate] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'123', N'425')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'345', N'345')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'567', N'986')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'768', N'008')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'008', NULL)
GO
*******************/

Related

How to insert more rows into a table

I need to insert many rows into a table. The table has 9 columns, and for each row the values are the same, except for one column (docunumber). I could perform the same query whenever it is necessary limiting myself to change only the specified column. For example:
insert into dpa_note (testo, DATACREAZIONE, IDUTENTECREATORE, IDRUOLOCREATORE, TIPOVISIBILITA, TIPOOGGETTOASSOCIATO,
IDOGGETTOASSOCIATO,IDPEOPLEDELEGATO, IDRFASSOCIATO)
values ('Documento validato con Verapdf', 3575, 252, 'T', 'D',--here docnumber one at a time--
, NULL, NULL)
But is there a way to pass all docnumbers together and perform the insert with only one statement?
You may use an INSERT INTO ... SELECT:
INSERT INTO dpa_note (testo, DATACREAZIONE, IDUTENTECREATORE, IDRUOLOCREATORE,
TIPOVISIBILITA, TIPOOGGETTOASSOCIATO, IDOGGETTOASSOCIATO, IDPEOPLEDELEGATO,
IDRFASSOCIATO)
SELECT 'Documento validato con Verapdf', 3575, 252, 'T', 'D', TIPOOGGETTOASSOCIATO,
NULL, NULL, NULL);
It isn't clear from your question which column you want to use from the existing table. I assumed it is TIPOOGGETTOASSOCIATO.

Loop through each column name from one table and insert that name into another table?

I have two tables. One table has a list of 500 columns. Another table references each column name like this
Select Top 1 * from MyReferenceTable
Which returns the results
(69, 'FirtName', 1, NULL)
(69, 'LastName', 2, NULL)
Where 'FirstName' is the name of the column from an actual table.
So I want to fill this reference table with the column names from the other table as so
Insert Into MyReferenceTable
FileId, ColumnName1, ColumnOrder, DefaultValue
Values(69, Select ColumnName From OtherTable? ,
Select Next Sequential Identity?, NULL)
My issue is how can I loop through the other table get the column name for each row, also insert an identity in sequentialOrder as ColumnOrder?
Typing out that insert statement manually for over 500 columns would take many moons.
This is a terrible idea, but the answer to your question is straight-forward:
INSERT INTO MyReferenceTabel (FileId, ColumnName1, ColumnOrder, DefaultValue)
SELECT 69, [name], [column_id], NULL
FROM sys.columns
WHERE [object_id] = OBJECT_ID('MyOtherTable')
Basically you craft a SELECT statement that returns the values you want, and then just add the INSERT statement over it.
But again, this smells of a terrible design choice that will bite you in the end. But it's still good to know how to get this information, so I'm posting this example here.

SQL Server where condition on column with separated values

I have a table with a column that can have values separated by ",".
Example column group:
id column group:
1 10,20,30
2 280
3 20
I want to create a SELECT with where condition on column group where I can search for example 20 ad It should return 1 and 3 rows or search by 20,280 and it should return 1 and 2 rows.
Can you help me please?
As pointed out in comments,storing mutiple values in a single row is not a good idea..
coming to your question,you can use one of the split string functions from here to split comma separated values into a table and then query them..
create table #temp
(
id int,
columnss varchar(100)
)
insert into #temp
values
(1,'10,20,30'),
(2, '280'),
(3, '20')
select *
from #temp
cross apply
(
select * from dbo.SplitStrings_Numbers(columnss,',')
)b
where item in (20)
id columnss Item
1 10,20,30 20
3 20 20
The short answer is: don't do it.
Instead normalize your tables to at least 3NF. If you don't know what database normalization is, you need to do some reading.
If you absolutely have to do it (e.g. this is a legacy system and you cannot change the table structure), there are several articles on string splitting with TSQL and at least a couple that have done extensive benchmarks on various methods available (e.g. see: http://sqlperformance.com/2012/07/t-sql-queries/split-strings)
Since you only want to search, you don't really need to split the strings, so you can write something like:
SELECT id, list
FROM t
WHERE ','+list+',' LIKE '%,'+#searchValue+',%'
Where t(id int, list varchar(max)) is the table to search and #searchValue is the value you are looking for. If you need to search for more than one value you have to add those in a table and use a join or subquery.
E.g. if s(searchValue varchar(max)) is the table of values to search then:
SELECT distinct t.id, t.list
FROM t INNER JOIN s
ON ','+t.list+',' LIKE '%,'+s.searchValue+',%'
If you need to pass those search values from ADO.Net consider table parameters.

Need help to get an insert statement in SQL Server

I would need to insert the non existing values to a Table.
Table name BarcodeSubgroup (single column table)
Column (nvarchar)
Sample data in the table
ProductSubGroupID
-----------------
F11WD
F77AH
G36CN
G37HJ
H11AA
H11AD
Now I need to insert the non existing values in the table.
Values want to be checked and inserted.
H11AA
H11AD
G78DE
G76DK
G41JA
B45JC
Query written
insert into BarcodeSubgroup
select
productsubgroupid
where
not exists ('G78DE', 'G76DK', 'G41JA',
'B45JC', 'H11AA', 'H11AD')
Now it should insert only the 4 non existing values.
You can do this with select . . . not exists:
insert into BarcodeSubgroup(productsubgroupid)
select productsubgroupid
from (values ('G78DE'), ('G76DK'), ('G41JA'), ('B45JC'), ('H11AA'), ('H11AD') ) v(productsubgroupid)
where not exists (select 1
from BarcodeSubgroup bs
where bs.productsubgroupid = v.productsubgroupid
);

SQL INSERT statement for TWO TABLES at time with INNER JOIN

I have two tables hello and login_table and below is their structure
user_info
-------
some_id | name | address
login_table
-------
id | username | password
some_id and id are autoincrement indexes.
Now how can i use INSERT statement with INNER JOIN in SQL
at present, i want add below data with same some_id and id
`name` = John
`address` = wall street
`username` = john123
`password` = passw123
below code shows, what i have tried so far.
insert into login_table lt
INNER JOIN user_info ui ON ui.some_id = lt.id
(ui.name, ui.address, lt.username, lt.password)
values
('John', 'wall street', 'john123', 'passw123')
And this is not the one value, i want to add more than one value at a time.. how can i achieve.
thanks for help.
If you need to perform the two INSERT operations atomically, use a transaction:
START TRANSACTION;
INSERT INTO login_table (username, password) VALUES ('john123', 'passw123');
INSERT INTO user_info (name, address) VALUES ('John', 'wall street');
COMMIT;
N.B. Your storage engine must support transactions for this to work (e.g. InnoDB).
To insert multiple values into a table at once, use the multiple rows form of INSERT. As stated in the manual:
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
The values list for each row must be enclosed within parentheses. The following statement is illegal because the number of values in the list does not match the number of column names:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3,4,5,6,7,8,9);
VALUE is a synonym for VALUES in this context. Neither implies anything about the number of values lists, and either may be used whether there is a single values list or multiple lists.
Insert to two tables is impossible. The second part of your question is possible: you can insert multiple rows in one statement like this:
insert into some_table(col1, col2) values (1,2), (3,4), (5,6);
USE [ERPDb]
GO
INSERT INTO [AAA].[UserRole] ([UserId], [RoleId])
SELECT u.Id, (SELECT Id FROM [AAA].[Role] WHERE Title = 'Employee') FROM [AAA].[User] u
INNER JOIN [dbo].[BaseDealer] bd ON u.Id = bd.Id
WHERE bd.DealerType = 0
GO