I have an employee table with multiple entries for the same person.
Using their SIN number you are able to determine if they are the same person.
Example:
Id Name SIN
1 John Smith 1234
2 John Smith 1234
3 Jess Jones 4321
I want to be able to copy everyone in this table, into a new table.
I want to create a new column (UserKey [GUID]) that is unique to the user who is in the table multiple times.
I want to use this new UserKey [GUID] instead of the SIN number.
Example:
Id Name UserKey (Guid)
1 John Smith 1234DFKJ2328LJFD
2 John Smith 1234DFKJ2328LJFD
3 Jess Jones 9543SLDFJ28EKJFF
I have no idea on how to approach this query. Any help would be great.
I am using MS SQL Server 2008.
Thanks.
You can just create a temp table, mapping SIN to a new GUID. Then you can join the original table with the mapping table, and create the new table from that.
# Create a table called #temp with the mappings SID => new GUID
SELECT SIN, newid() UserKey INTO #temp FROM (SELECT DISTINCT SIN FROM Table1) a
# ...and join that and the original table to a new table.
SELECT id, name, userkey
INTO NewTable
FROM Table1 t1
JOIN #temp t2
ON t1.SIN = t2.SIN
SQLFiddle here.
Related
I'm using Access 2016 to view data from a table on our SQL server. I have a massive audit log where the record being viewed is represented by a "FolderID" field. I have another table that has values for the FolderID (represented as "fid") along with columns identifying the record's name and other ID numbers.
I want to be able to replace the FolderID value in the first table with CUSTOMER_NAME value from the second table so I know what's being viewed at a glance.
I've tried googling different join techniques to build a query that will accomplish this, but my google-fu is weak or I'm just not caffeinated enough today.
Table 1.
EventTime EventType FolderID
4/4/2019 1:23:39 PM A 12345
Table 2
fid acc Other_ID Third_ID CUSTOMER_NAME
12345 0 9875 12345678 Doe, John
Basically I want to query Table 2 to search for fid using the value in Table 1 for FolderID, and I want it to respond with the CUSTOMER_NAME associated with the FolderID/fid. The result would look like:
EventTime EventType FolderID
4/4/2019 1:23:39 PM A Doe, John
I'm stupid because I thought I was too smart to use the freaking Query Wizard. When I did, and it prompted me to create relationships and actually think about what I was doing, it came up with this.
SELECT [table1].EventTime, [table1].EventType, [table1].FolderID, [table1].ObjRef, [table1].AreaID, [table1].FileID, [table2].CUSTOMER_NAME, [table2].fid FROM [table2]
LEFT JOIN [table1] ON [table2].[fid] = [table1].[FolderID];
You can run this query and check if it helps!.
Select EventTime, EventType , CUSTOMER_NAME AS FolderID FROM Table1, Table2 Where Table1.FolderID = Table2.fid;
Basically, 'AS' is doing what you want here as you can rename your column to whatever you want.
The short version is I'm trying to map from a flat table to a new set of tables with a stored procedure.
The long version: I want to SELECT records from an existing table, and then for each record INSERT into a new set of tables (most columns will go into one table, but some will go to others and be related back to this new table).
I'm a little new to stored procedures and T-SQL. I haven't been able to find anything particularly clear on this subject.
It would appear I want to something along the lines of
INSERT INTO [dbo].[MyNewTable] (col1, col2, col3)
SELECT
OldCol1, OldCol2, OldCol3
FROM
[dbo].[MyOldTable]
But I'm uncertain how to get that to save related records since I'm splitting it into multiple tables. I'll also need to manipulate some of the data from the old columns before it will fit into the new columns.
Thanks
Example data
MyOldTable
Id | Year | Make | Model | Customer Name
572 | 2001 | Ford | Focus | Bobby Smith
782 | 2015 | Ford | Mustang | Bobby Smith
Into (with no worries about duplicate customers or retaining old Ids):
MyNewCarTable
Id | Year | Make | Model
1 | 2001 | Ford | Focus
2 | 2015 | Ford | Mustang
MyNewCustomerTable
Id | FirstName | LastName | CarId
1 | Bobby | Smith | 1
2 | Bobby | Smith | 2
I would say you have your OldTable Id to preserve in new table till you process data.
I assume you create an Identity column Id on your MyNewCarTable
INSERT INTO MyNewCarTable (OldId, Year, Make, Model)
SELECT Id, Year, Make, Model FROM MyOldTable
Then, join the new table and above table to insert into your second table. I assume your MyNewCustomerTable also has Id column with Identity enabled.
INSERT INTO MyNewCustomerTable (CustomerName, CarId)
SELECT CustomerName, new.Id
FROM MyOldTable old
JOIN MyNewCarTable new ON old.Id = new.OldId
Note: I have not applied Split of Customer Name to First Name and
Last Name as I was unsure about existing data.
If you don't want your OldId in MyNewCarTable, you can DELETE it
ALTER TABLE MyNewCarTable DROP COLUMN OldId
You are missing a step in your normalization. You do not need to duplicate your customer information per vehicle. You need three tables for 4th Normal form. This will reduce storage size and more importantly allow an update to the customer data to take place in one location.
Customer
CustomerID
FirstName
LastName
Car
CarID
Make
Model
Year
CustomerCar
CustomerCarID
CarID
CustomerID
DatePurchaed
This way you can have multiple owners per car, multiple cars per owner and only one record needs to be updated per car and or customer...4th Normal Form.
If I am reading this correctly, you want to take each row from table 1, and create a new record into table A using some of that row data, and then data from the same original row into Table B, Table C but referencing back to Table A again?
If that's the case, you will create TableA with an Identity and make thats the PK.
Insert the required column data into that table and use the #IDENTITY to retrieve the last identity value, then you will insert the remaining data from the original table into the other tables, TableB, TableC, etc. and use the identity you retrieved from TableA as the FK in the other tables.
By Example:
Table 1 has columns col1, col2, col3, col4, col5
Table A has TabAID, col1, col2
Table B has TabBID, TabAID, col3
TableC has TabCID, TabAID, col4
When the first row is read, the values for col1 & col2 are inserted into TableA.
The Identity is captured from that row inserted, and then value for col3 AND the identity are entered into TableB, and then value for col4 AND the identity are entered into TableC.
This is a standard data migration technique for normalizing data.
Hope this assists,
If I have an address table and a cities lookup table and the address table has the cities in text instead of a foreign key, how would I replace the text with its counterpart in the lookup table?
Example:
Table luCities:
ID Name
--------------------
1 New Orleans
2 Portland
3 Seattle
Table Addresses:
ID Street City State Zip
--------------------------------------------------
1 123 main st. New Orleans OR 96556
should become
ID Street CityId State Zip
--------------------------------------------------
1 123 main st. 1 OR 96556
I have roughly 250 rows to match multiple cities with, so I'm hoping that a single UPDATE/SET statement can be used to match and modify them.
I believe you are looking for an update-join. If you add CityID to addresses as a FK to luCities, you can run this:
UPDATE Addresses SET
CityID = c.ID
FROM Addresses A
inner join luCities C on A.City = C.Name
Once everything looks correct, you can drop the old City column if you like.
I have two tables one is master and another one is details table , Details table contain master table id as reference
Here is my table
**Table_Customer**
CustomerId CustomerName
1 A
2 B
**Table_CustomerRelatives**
RelativesId CustomerId RelativesName Address
1 1 M xyz
2 1 N mno
3 2 L pqr
4 2 O ghy
Here CustomerId and RelativesId are identity columns so automatic generating columnvalue
Here I have two temp tables like
**TembreryTableCustomer**
CustomerId CustomerName
1 F
2 G
3 H
**TembreryTableDetails**
CustomerId RelativesName Address
1 S fgg
1 T dfg
2 U ghj
3 V jkl
3 W rty
How can Insert Temp table data to my tables with identity.
here i want to insert rows of temp table customer and get identity value then insert temp table details data using temp table customer identity.
You can use the output clause of the merge statement to build a mapping of the temporary customer's id to the new id.
declare #Map table (Old int, New int);
;merge Table_Customer dest
using TembreryTableCustomer src
on dest.CustomerName = src.CustomerName
when not matched then
insert (CustomerName) values (CustomerName)
output inserted.CustomerID, src.CustomerID
into #map;
insert Table_CustomerRelatives
(CustomerId, RelativesName, Address)
select m.New
, t.RelativesName
, t.Address
from TembreryTable2 t
join #Map m
on t.CustomerID = m.Old;
Example at SQL Fiddle.
There are several approaches depending on the version of SQL and your preference for where to put the work.
I find using sequences far easier to use than identity columns. You can use the same sequence in your temp tables as in your persistent tables so there's no "fixup" to do.
Barring that, you can insert into the persistent table with an output clause to capture the newly assigned IDs. From the link, check out example "E". The salient feature is to output persistent IDs alongside the temp table IDs.
SQL Server 2000. Single table has a list of users that includes a unique user ID and a non-unique user name.
I want to search the table and list out any users that share the same non-unique user name. For example, my table looks like this:
ID User Name Name
== ========= ====
0 parker Peter Parker
1 parker Mary Jane Parker
2 heroman Joseph (Joey) Carter Jones
3 thehulk Bruce Banner
What I want to do is do a SELECT and have the result set be:
ID User Name Name
== ========= ====
0 parker Peter Parker
1 parker Mary Jane Parker
from my table.
I'm not a T-SQL guru. I can do the basic joins and such, but I'm thinking there must be an elegant way of doing this. Barring elegance, there must be ANY way of doing this.
I appreciate any methods that you can help me with on this topic. Thanks!
---Dan---
One way
select t1.* from Table t1
join(
select username from Table
group by username
having count(username) >1) t2 on t1.username = t2.username
The simplest way I can think of to do this uses a sub-query:
select * from username un1 where exists
(select null from username un2
where un1.user_name = un2.user_name and un1.id <> un2.id);
The sub-query selects all names that have >1 row with that name... outer query selects all the rows matching those IDs.
SELECT T.*
FROM T
, (SELECT Dupe_candidates.USERNAME
FROM T AS Dupe_candidates
GROUP BY Dupe_candidates.USERNAME
HAVING count(*)>1
) Dupes
WHERE T.USERNAME=Dupes.USERNAME
You can try the following:
SELECT *
FROM dbo.Person as p1
WHERE
(SELECT COUNT(*) FROM dbo.Person AS p2 WHERE p2.UserName = p1.UserName) > 1;