RashItIs
RashItIs

Reputation: 87

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

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?

Upvotes: 0

Views: 920

Answers (1)

Gerard
Gerard

Reputation: 301

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
*******************/

Upvotes: 1

Related Questions