Filling information from same and other tables in SQL - sql

For my further work I need to create a lookup table where all the different IDs my data has (because of different sources) are noted.
It has to look like this:
Lookup_Table:
| Name | ID_source1 | ID_source2 | ID_source3 |
-----------------------------------------------
| John | EMP_992 | AKK81239K | inv1000003 |
Note, that Name and ID_Source1 are coming from the same table. The other IDs are coming from different tables. They share the same name value, so e.g. source 2 looks like this:
Source2 Table:
| Name | ID |
--------------------
| John | AKK81239K |
What is the SQL code to accomplish this? Im using Access and it doesnt seem to work with this code for source 2:
INSERT INTO Lookup_Table ([ID_Source2])
SELECT [Source2].[ID]
FROM Lookup_Table LEFT JOIN [Source2]
ON [Lookup_Table].[Name] = [Source2].[Name]
It just adds the ID from Source2 in a new row:
| Name | ID_source1 | ID_source2 | ID_source3 |
-----------------------------------------------
| John | EMP_992 | | |
| | | AKK81239K | |
Hope you guys can help me.

You're looking for an UPDATE query, not an INSERT query.
An UPDATE query updates existing records. An INSERT query inserts new records into a table.
UPDATE Lookup_Table
INNER JOIN [Source2] ON [Lookup_Table].[Name] = [Source2].[Name]
SET [ID_Source2] = [Source2].[ID]

Related

Sql Server how to find values in different tables that have different suffix

I'm struggling to find a value that might be in different tables but using UNION is a pain as there are a lot of tables.
[Different table that contains the suffixes from the TestTable_]
| ID | Name|
| -------- | -----------|
| 1 | TestTable1 |
| 2 | TestTable2 |
| 3 | TestTable3 |
| 4 | TestTable4 |
TestTable1 content:
| id | Name | q1 | a1 |
| -------- | ---------------------------------------- |
| 1 | goose | withFeather? |featherID |
| 2 | rooster| withoutFeather?|shinyfeatherID |
| 3 | rooster| age | 20 |
TestTable2 content:
| id | Name | q1 | a1 |
| -------- | ---------------------------------------------------|
| 1 | brazilian_goose | withFeather? |featherID |
| 2 | annoying_rooster | withoutFeather?|shinyfeatherID |
| 3 | annoying_rooster | no_legs? |dead |
TestTable3 content:
| id | Name | q1 | a1 |
| -------- | ---------------------------------------- |
| 1 | goose | withFeather? |featherID |
| 2 | rooster| withoutFeather?|shinyfeatherID |
| 3 | rooster| age | 15 |
Common columns: q1 and a1
Is there a way to parse through all of them to lookup for a specific value without using UNION because some of them might have different columns?
Something like: check if "q1='age'" exists in all those tables (from 1 to 50)
Select q1,*
from (something)
where q1 exists in (TestTable_*)... or something like that.
If not possible, not a problem.
You could use dynamic SQL but something I do in situations like this where I have a list of tables that I want to quickly perform the same actions on is to either use a spreadsheet to paste the list of tables into and type a query into the cell with something like #table then use the substitute function to replace it.
Alternative I just paste the list into SSMS and use SHIFT+ALT+ArrowKey to select the column and start typing stuff out.
So here is my list of tables
Then I use that key combo. As you can see my cursor has now selected all those rows.
Now I can start typing and all rows selected will get the input.
Then I just go to the other side of the table names and repeat the action
It's not a perfect solution but it's quick a quick and dirty way of doing something repetitive quickly.
If you want to find all the tables with that column name you can use information schema.
Select table_name from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'q1'
Given the type of solution you are after I can offer a method that I've had to use on legacy systems.
You can query sys.columns for the name of the column(s) you need to find in N tables and join using object_id to sys.tables where type='U'. This will give you a list of table names.
From this list you can then build a working query for each table, and depending on your requirements (is this ad-hoc?) either just manually execute it yourself of build a procedure that will do it for you using sp_executesql
Eg
select t.name, c.name
into #workingtable
from sys.columns c
join sys.tables t on t.object_id=c.object_id
where c.name in .....
psudocode:
begin loop while rows exist in #working table
select top 1 row from #workingtable
set #sql=your query specific to that table and column(s)
exec(#sql) / sp_executesql / try/catch as necessary
delete row from working table
end loop
Hopefully that give ideas at least for how you might implement your requirements.

How to map(reference) identical data but different PK?

I'm doing some database data migration.
The problem is the records (ContactsID) has changed - because of PK increment as well as mixed data (I can't just put the SQL result next to each other etc...)
Here is an example
Data in Original table
+-----------+-------------+
| CompanyID | CompanyName |
+-----------+-------------+
| 1 | Facebook |
+-----------+-------------+
In New Database
+-----------+-------------+
| CompanyID | CompanyName |
+-----------+-------------+
| 9 | Facebook |
+-----------+-------------+
I'm having issues when it comes to importing matching records from another table that reference the Data in the original database.
Is there a tool I can use to help me match the records?
Here is my desired result
+-----------+-------------+-----+
| CompanyID | CompanyName | Key |
+-----------+-------------+-----+
| 1 | Facebook | 9 |
+-----------+-------------+-----+
I will use the key import better.
There is join:
select o.CompanyName, o.CompanyID, n.CompanyID
from original o join
newdatabase n
on o.CompanyName = n.CompanyName

Replacing data from one column in a table with another using an unrelated tables

I am working on updating an existing system which will display a table on a web from to show who has called out of work. The data is pulled from a database consisting of two tables. One contains the actual data recorded from the call, and the other is a 'Legend' of sorts so convert a single digit in a column to a plain text description. For example:
Options Table
|---------------------|------------------|------------------|
| LevelName | OptionNo | Description |
|---------------------|------------------|------------------|
| LorA | 1 | Late |
|---------------------|------------------|------------------|
| LorA | 2 | Absent |
|---------------------|------------------|------------------|
| TorT | 1 | Today |
|---------------------|------------------|------------------|
| TorT | 2 | Tomorrow |
|---------------------|------------------|------------------|
The second table has a layout like this (only showing relevant fields):
CallData Table
|---------------------|------------------|------------------|
| EmployeeName | Todaytomorrow | Late_Or_Absent |
|---------------------|------------------|------------------|
| John | 1 | 1 |
|---------------------|------------------|------------------|
| Jane | 2 | 2 |
|---------------------|------------------|------------------|
What I am having trouble with is how to somehow relate the two tables in order to replace the integer representation in the CallLog Table with the corresponding value in the Options Table.
I have tried creating a temporary table by selecting all from both tables, however when I attempt to replace the values only those which happen to align after the join are replaced.
Here is the SQL I currently have:
/*Create TempTable to be updated*/
SELECT * INTO #tempStore FROM CallData, [Options]
WHERE CallData.EmpName IS NOT NULL AND call_completed = '1'
/*Query Pertinant Info*/
SELECT [CallinID], [EmpName], [TodayTomorrow] AS [When], [Late_Or_Absent] AS [Type], [Late_Reason] AS [Reason],
[Absent_Reason], [Early_Reason], [Contact_Number], [Comment], [created_dt] FROM [#tempStore]
/*Update Type to varChar*/
ALTER TABLE [#tempStore]
ALTER COLUMN [TodayTomorrow] nvarchar(20)
/*Perform TorT Update*/
UPDATE [#tempStore] SET [#tempStore].TodayTomorrow = [#tempStore].[Description]
WHERE [#tempStore].LevelName = 'TorT' AND [#tempStore].TodayTomorrow = CONVERT(nvarchar(1), [#tempStore].[OptionNo])
Any and all help is much appreciated.
For this example, I think the following will work:
select cd.EmployeeName
,optTT.Description TodayTomorrow
,optLE.Description Late_or_Absent
from CallData as cd
join [Options] as optTT on optTT.OptionNo = cd.Late_or_Absent and optTT.LevelName = 'TorT'
join [Options] as optLE on optLE.OptionNo = cd.TodayTomorrow and optLE.LevelName = 'LorA'
Edited: added joining on different levels. If there are more than two levels, a more general solution is required.

BigQuery Match Table Lookup for DCM Data Transfer

With DCM's Data Transfer v2 you get 3 main tables of data in GCS:
p_activity_166401
p_click_166401
p_impression_166401
Along with a plethora of match tables like:
p_match_table_advertisers_166401
p_match_table_campaigns_166401
Table 1: p_activity_166401
Row | Event_time | User_ID | Advertiser_ID | Campaign_ID |
------ | ------------- | ------- | ------------- | ----------- |
1 | 149423090566 | AMsySZa | 5487307 | 9638421 |
2 | 149424804284 | 2vmdsXS | 5487307 | 10498283 |
Table 2: p_match_table_advertisers_166401
Row | Advertiser_ID | Advertiser |
------ | ------------- | ----------- |
1 | 5487307 | Company A |
2 | 5487457 | Company B |
How do I reference a value from Table 1 in Table 2 and return the value from Table 2 in a query?
I'd like a result like:
Row | Advertiser | User_ID |
------ | ---------- | ----------- |
1 | Company A | AMsySZa |
2 | Company A | 2vmdsXS |
Been searching around here and online and I just can't seem to find a clear reference on how to do the lookups across table, apologies in advance is this is a really simple thing I'm missing :)
EDIT
So with a nudge in the right direction I have found the JOIN function...
SELECT
*
FROM
[dtftv2_sprt.p_activity_166401]
INNER JOIN
[dtftv2_sprt.p_match_table_advertisers_166401]
ON
[p_activity_166401.Advertiser_ID] =
p_match_table_advertisers_166401.Advertiser_ID]
LIMIT
100;
Error: Field 'p_activity_166401.Advertiser_ID' not found.
That is definitely a field in the table.
So this query works great in creating a view with all the data in it.
SELECT
*
FROM
[dtftv2_sprt.p_activity_166401]
INNER JOIN
[dtftv2_sprt.p_match_table_advertisers_166401]
ON
dtftv2_sprt.p_activity_166401.Advertiser_ID = dtftv2_sprt.p_match_table_advertisers_166401.Advertiser_ID;
Using the view I can now run smaller queries to pull the data I want out. Thanks for guiding me in the right direction Mikhail Berlyant.

Oracle Recursive Select to Find Current ID Associated with a Customer

I have a table that contains the history of Customer IDs that have been merged in our CRM system. The data in the historical reporting Oracle schema exists as it was when the interaction records were created. I need a way to find the Current ID associated with a customer from potentially an old ID. To make this a bit more interesting, I do not have permissions to create PL/SQL for this, I can only create Select statements against this data.
Sample Data in customer ID_MERGE_HIST table
| OLD_ID | NEW_ID |
+----------+----------+
| 44678368 | 47306920 |
| 47306920 | 48352231 |
| 48352231 | 48780326 |
| 48780326 | 50044190 |
Sample Interaction table
| INTERACTION_ID | CUST_ID |
+----------------+----------+
| 1 | 44678368 |
| 2 | 48352231 |
| 3 | 80044190 |
I would like a query with a recursive sub-query to provide a result set that looks like this:
| INTERACTION_ID | CUST_ID | CUR_CUST_ID |
+----------------+----------+-------------+
| 1 | 44678368 | 50044190 |
| 2 | 48352231 | 50044190 |
| 3 | 80044190 | 80044190 |
Note: Cust_ID 80044190 has never been merged, so does not appear in the ID_MERGE_HIST table.
Any help would be greatly appreciated.
You can look at CONNECT BY construction.
Also, you might want to play with recursive WITH (one of the descriptions: http://gennick.com/database/understanding-the-with-clause). CONNECT BY is better, but ORACLE specific.
If this is frequent request, you may want to store first/last cust_id for all related records.
First cust_id - will be static, but will require 2 hops to get to the current one
Last cust_id - will give you result immediately, but require an update for the whole tree with every new record