inserting data in table in sql from another table records - sql

I have 2 tables...
UserMaster (UserID, Fname)
SharingMaster (SharingID, UserID)
I want all data inserted into SharingMaster that UserID are available in UserMaster... means each row per userid from usermaster....
For example.. if I have data in both tables
UserMaster:
UserID Fname
-----------------------
1 Abc
4 Def
5 asda
8 fgdfgdf
and SharingMaster as follows
SharingID UserID
-------------------------
6 1
9 4
8 5
8 8
so what is query for that?

If you're trying to insert UserIDs into SharingMaster from UserMaster that are not already present, here's a way to do it in SQL Server. My only assumption is that the SharingID is an IDENTITY column that will auto populate.
INSERT INTO dbo.SharingMaster
(UserID
, Fname
)
SELECT UserID
, Fname
FROM UserMaster
WHERE NOT EXISTS ( SELECT 1
FROM SharingMaster
WHERE SharingMaster.UserID = UserMaster.UserID )
Then again, since the scenario was a little ambiguous, here are some other options. My assumption here is that "all the data" you referred to was the Fname column from UserMaster.
If you wanted to insert or overwrite existing data for IDs already in sharing master:
INSERT INTO SharingMaster
(Fname
)
SELECT Fname
FROM UserMaster
JOIN SharingMaster
ON UserMaster.UserID = SharingMaster.SharingID
And as a bonus, if you're on SQL Server 2008 R2 or above, you can use the MERGE statement:
MERGE dbo.SharingMaster AS TARGET
USING
(SELECT UserID
, Fname
FROM dbo.UserMaster
) AS SOURCE (UserID, Fname)
ON (TARGET.UserID = SOURCE.UserID)
WHEN MATCHED
THEN
UPDATE SET
Fname = SOURCE.Fname
WHEN NOT MATCHED
THEN
INSERT (UserID, Fname)
VALUES
(SOURCE.UserID
, SOURCE.Fname
);

Related

How to merge users in PostgreSQL

I need to make something to merge some users in PGSQL but I think that pgsql don't own the MERGE property. I just want to know how to make two users to be matched like this :
id | name | username | mail
1 | toto | tata | toto.tata#gmail.com
2 | titi | tutu | titi.tutu#gmail.com
Here I want to chose which data I would like I want to say that I want to merge only username from 2 to 1 so the result would be :
id | name | username | mail
1 | toto | tutu | toto.tata#gmail.com
You just need to select all the columns for first id and the column you need with second id will be a subquery in select list. Please check below answer for selecting merged result.
Schema and insert statements:
create table users (id int , name varchar(50), username varchar(50), mail varchar(50));
insert into users values (1 , 'toto' , 'tata' , 'toto.tata#gmail.com');
insert into users values (2 , 'titi' , 'tutu' , 'titi.tutu#gmail.com');
Query:
select id,name,(select username from users where id=2) username,mail from users where id=1
Output:
id
name
username
mail
1
toto
tutu
toto.tata#gmail.com
db<fiddle here
To merge the rows within the table you can first update first row with data from second row then delete the second row. Try this:
Schema and insert statements:
create table users (id int , name varchar(50), username varchar(50), mail varchar(50));
insert into users values (1 , 'toto' , 'tata' , 'toto.tata#gmail.com');
insert into users values (2 , 'titi' , 'tutu' , 'titi.tutu#gmail.com');
Update query:
update users set username=(select username from users where id=2) where id=1;
delete from users where id=2;
Select query:
select * from users
id
name
username
mail
1
toto
tutu
toto.tata#gmail.com
db<fiddle here
You could use aggregation:
select min(id) as id,
max(name) filter (where id = 1) as name,
max(username) filter (where id = 2) as username,
max(mail) filter (where id = 1) as mail
from t
where id in (1, 2);
This assumes that you want to pull particular column values from particular ids.
Or you could use join:
select t1.id, t1.name, t2.username, t1.mail
from t t1 join
t t2
on t1.id = 1 and t2.id = 2;
If you actually want to change the data, use update and delete:
update t t1
set username = t2.username
from t t2
where t1.id = 1 and t2.id = 2;
delete from t
where t.id = 2;
Here is a db<>fiddle.

How to use nested Insert based on select statement using ms sql server

I have multiple records in Select statement, I want to insert these records in two different tables based on Primary keys.
I have three tables Roles, MenuMaster and MenuChild as under
Roles:
- RoleID(PK) RoleName
- 1 Sales
- 2 Marketing
- 3 IT
MenuMaster:
- MID(PK) MFormName RoleID(FK)
- 1 Orders 1
- 2 SMM 2
- 3 Help 1
MenuChild:
- CID(PK) FormName, MID(FK)
- 1 NewOrder.aspx 1
- 2 RepeatOrder.aspx 1
- 3 Advertise.aspx 2
I want to create a new merge Role like '4, Sales & Marketing' and copy all records of RoleID=1 and RoleID=2 from MenuMaster to 'Sales & Marketing' RoleID and copy MenuChild record against new Inserted record MenuID
Create the role and use a temp table to populate the other tables:
INSERT INTO dbo.Roles (RoleName)
VALUES ('Sales & Marketing')
SELECT
'Sales & Marketing' as RoleName,
mm.MenuId,
mm.MFormName,
SCOPE_IDENTITY() AS PK
INTO #tmp
FROM dbo.MenuMaster mm
WHERE mm.RoleId in (1,2)
INSERT INTO dbo.MenuMaster (MFormName, RoleId)
SELECT t.MFormName, t.PK from #tmp t
UPDATE #tmp SET PK = SCOPE_IDENTITY()
INSERT INTO dbo.MenuChild(FormName, MenuId)
SELECT t.MFormName, t.PK from #tmp t
This is a little ugly because I'm not sure I completely understood your requirement. You can also use a CTE, but after the first INSERT into MenuMaster, you will need to create another CTE

One SQL statement for counting the records in the master table based on matching records in the detail table?

I have the following master table called Master and sample data
ID---------------Date
1 2014-09-07
2 2014-09-07
3 2014-09-08
The following details table called Details
masterId-------------Name
1 John Walsh
1 John Jones
2 John Carney
1 Peter Lewis
3 John Wilson
Now I want to find out the count of Master records (grouped on the Date column) whose corresponding details record with Name having the value "John".
I cannot figure how to write a single SQL statement for this job.
**Please note that join is needed in order to find master records for count. However, such join creates duplicate master records for count. I need to remove such duplicate records from being counted when grouping on the Date column in the Master table.
The correct results should be:
count: grouped on Date column
2 2014-09-07
1 2014-09-08
**
Thanks and regards!
This answer assumes the following
The Name field is always FirstName LastName
You are looking once and only once for the John firstname. The search criteria would be different, pending what you need
SELECT Date, Count(*)
FROM tblmaster
INNER JOIN tbldetails ON tblmaster.ID=tbldetails.masterId
WHERE NAME LIKE 'John%'
GROUP BY Date, tbldetails.masterId
What we're doing here is using a wilcard character in our string search to say "Look for John where any characters of any length follows".
Also, here is a way to create table variables based on what we're working with
DECLARE #tblmaster as table(
ID int,
[date] datetime
)
DECLARE #tbldetails as table(
masterID int,
name varchar(50)
)
INSERT INTO #tblmaster (ID,[date])
VALUES
(1,'2014-09-07'),(2,'2014-09-07'),(3,'2014-09-08')
INSERT INTO #tbldetails(masterID, name) VALUES
(1,'John Walsh'),
(1,'John Jones'),
(2,'John Carney'),
(1,'Peter Lewis'),
(3,'John Wilson')
Based on all comments below, this SQL statement in it's clunky glory should do the trick.
SELECT date,count(t1.ID) FROM #tblmaster mainTable INNER JOIN
(
SELECT ID, COUNT(*) as countOfAll
FROM #tblmaster t1
INNER JOIN #tbldetails t2 ON t1.ID=t2.masterId
WHERE NAME LIKE 'John%'
GROUP BY id)
as t1 on t1.ID = mainTable.id
GROUP BY mainTable.date
Is this what you want?
select date, count(distinct m.id)
from master m join
details d
on d.masterid = m.id
where name like '%John%'
group by date;

SQL 2008: Insert multiple rows based on specific criteria

I am trying to clone user permissions. The permissions are driven from a table with only 2 columns, userid and groupid. Both are foreign keys.
Is it possible to insert multiple rows based on criteria? Let's say:
USERID GROUPID
1 A
1 B
1 C
1 D
I would like to insert rows to give USER 2 the same GROUPS as USER 1.
Does this get me close?
INSERT INTO ide_usergroup_assoc (userid, groupid)
VALUES ('USERID I PROVIDE', (SELECT ide_usergroup_assoc.groupid from ide_usergroup_assoc WHERE ide_usergroup_assoc.userid = 'USERID TO BE CLONED'))
insert into ide_usergroup_assoc (userid, groupid)
select 2, groupid
from ide_usergroup_assoc
where userid = 1

Duplicate a row in SQL?

OK I have a table that has two columns, userID and courseID. It is used to assign training courses to a user. It looks like this:
userid courseid
0 1
0 3
0 6
1 1
1 4
1 5
so user 0 is assigned to courses 1,3,6 and user 1 is assigned to 1, 4 5
anyways I need to take every user that is assigned to 6 and create a new row that has that userid and courseid 11, basically assigning every user who is currently assigned to 6 to also be assigned to 11
for some reason (I did not create this database) both rows are marked as primary keys, and some statements I have tried have thrown an error because of this, what the heck is the deal?
oh maybe it is because there are a few users that are already assigned to 11 so it is choking on those maybe?
please help
Insert Into TableName (userID, courseID)
Select userID, 11 From TableName Where courseID=6;
Also, I'm a bit confused by your comment that both are primary keys. Both rows can be part of the primary key or both can be Unique keys but they cannot both be a primary key. As far as errors go, it is probably because the query tried to insert rows that were duplicates of already existing rows. To eliminate this possibility you could do this:
Insert Into TableName (userID, courseID)
Select userID, 11 From TableName Where courseID=6
AND (userID not in (Select userID From TableName Where courseID=11))
Depending on your database this could work too:
INSERT OR IGNORE INTO TableName (userID, courseID)
SELECT userID, 11 FROM TableName WHERE courseID=6;
Anyway, there you go.
insert into TableName (userId, courseId)
select userId, 11
from TableName
where courseId = 6
and not exists (
select 1
from TableName nested
where nested.userId = TableName.UserId
and nested.courseId = 11
)
Selects all users that are assigned to courseId 6 but are not yet assigned to courseId 11 and inserts a new record into the table for them for courseId 11.
This should help:
INSERT
INTO [table]
(
userid,
courseid
)
SELECT userid,
11
FROM [table]
WHERE courseid = 6
AND userid NOT IN
(SELECT userid
FROM [table]
WHERE courseid = 11
);
This will select all users in course 6 not in course 11 and add them with course 11 to the table.