INSERT INTO from two tables into one empty table with foreign key constraints - sql

I have a table called PurchaseOrderAccount that is empty. I need to insert the Account code from a table called DailyCosts. Also, I need to Insert a PurchaseOrderID from PurchaseOrder.ID. These are both foreign key restraints. No columns will accept Null. This is what I have:
Insert Into PurchaseOrderAccount (WellID, JobID,ID,PurchaseOrderID,AccountCode)
Select DailyCosts.WellID,
DailyCosts.JobID,
NEWID(),
PurchaseOrder.ID,
DailyCosts.AccountCode
From DailyCosts
inner join
PurchaseOrder
on DailyCosts.Notes =PurchaseOrder.PONumber
Join
PurchaseOrderDailyCost
On DailyCosts.DailyCostID = PurchaseOrderDailyCost.DailyCostID
Where DailyCosts.WellID = '24A-23'
Group By DailyCosts.WellID,
DailyCosts.JobID,
PurchaseOrder.ID,
DailyCosts.AccountCode;
With this, I get 191 records. I only want unique AccountCodes from DailyCosts which are 54. I would appreciate any direction.

I feel that you would have to remove DailyCosts.JobID in the 'Group By' if you want all unique combinations of DailyCosts.AccountCode and PurchaseOrder.ID.
As you have filtered DailyCosts.WellID = '24A-23', a group by should not affect it.
Insert Into PurchaseOrderAccount (WellID, ID,PurchaseOrderID,AccountCode)
Select DailyCosts.WellID,
NEWID(),
PurchaseOrder.ID,
DailyCosts.AccountCode
From DailyCosts
inner join
PurchaseOrder
on DailyCosts.Notes =PurchaseOrder.PONumber
Join
PurchaseOrderDailyCost
On DailyCosts.DailyCostID = PurchaseOrderDailyCost.DailyCostID
Where DailyCosts.WellID = '24A-23'
Group By DailyCosts.WellID,
PurchaseOrder.ID,
DailyCosts.AccountCode;
Here, I believe that there would be multiple JobID's causing your total number to be coming to 191, instead of the expected 41. Please let me know if this works for you.

Related

Suggestion to make a massive insert

I have the tables below:
tb_profile tb_mbx tb_profile_mbx tb_profile_cd
id id id_profile id_perfil
cod_mat mbx id_mbx id_cd (matches id_mbx)
concil bp
masc
I need to create a query that when validating that the id_cd 1,2,4,5
and 6 exists in tb_profile_cd, perform an insert in the
tb_profile_mbx table with the cod_matrix parameters of the tb_profile
table.
Remembering that each concil has its ID in the tb_mbx table and a
concil has many cod_mat.
Another point is that the concil id_mbx represents the id_cd of the
tb_profile_cd table.
One more point is that as I said above, that a concil has many
cod_mat. I have around 20 thousand records for each concil.
For my need, try to consult the query below, but Oracle returned an error:
insert into tb_profile_mbx values (seq_profile_mbx.nextval,
(select id from tb_profile where concil like '%NEXXERA%')
,(select id from tb_mbx where mbx like '%NEXXERA%')
,null
,null);
ORA-01427: single line subquery returns more than one line
Would there be another way to do this query?
Thanks in advance!
You can insert all matching combinations of matches using:
insert into tb_profile_mbx (id_profile, id_mbx)
select p.id, m.id
from tb_profile p join
tb_mbx m
on p.concil like '%NEXXERA%' and m.mbx like '%NEXXERA%';
I would recommend running the select to see if it returns the values you want.
You only show two columns for tb_profile_mbx, so I've only included two columns in the insert.

How do I insert data from one table to another when there is unequal number of rows in one another?

I have a table named People that has 19370 rows with playerID being the primary column. There is another table named Batting, which has playerID as a foreign key and has 104324 rows.
I was told to add a new column in the People table called Total_HR, which is included in the Batting table. So, I have to insert that column data from the Batting table into the People table.
However, I get the error:
Msg 515, Level 16, State 2, Line 183 Cannot insert the value NULL into
column 'playerID', table 'Spring_2019_BaseBall.dbo.People'; column
does not allow nulls. INSERT fails. The statement has been terminated.
I have tried UPDATE and INSERT INTO SELECT, however got the same error
insert into People (Total_HR)
select sum(HR) from Batting group by playerID
I expect the output to populate the column Total_HR in the People table using the HR column from the Batting table.
You could use a join
BEGIN TRAN
Update People
Set Total_HR = B.HR_SUM
from PEOPLE A
left outer join
(Select playerID, sum(HR) HR_SUM
from Batting
group by playerID) B on A.playerID = B.playerID
Select * from People
ROLLBACK
Notice that I've put this code in a transaction block so you can test the changes before you commit
From the error message, it seems that playerID is a required field in table People.
You need to specify all required fields of table People in the INSERT INTO clause and provide corresponding values in the SELECT clause.
I added field playerID below, but you might need to add additional required fields as well.
insert into People (playerID, Total_HR)
select playerID, sum(HR) from Batting group by playerID
It is strange, however, that you want to insert rows in a table that should already be there. Otherwise, you could not have a valid foreign key on field playerID in table Batting... If you try to insert such rows from table Batting into table People, you might get another error (violation of PRIMARY KEY constraint)... Unless... you are creating the database just now and you want to populate empty table People from filled/imported table Batting before adding the actual foreign key constraint to table People. Sorry, I will not question your intentions. I personally would consider to update the query somewhat so that it will not attempt to insert any rows that already exist in table People:
insert into People (playerID, Total_HR)
select Batting.playerID, sum(Batting.HR)
from Batting
left join People on People.playerID = Batting.playerID
where People.playerID is null and Batting.playerID is not null
group by playerID
You need to calculate the SUM and then join this result to the People table to bring into the same rows both Total_HR column from People and the corresponding SUM calculated from Batting.
Here is one way to write it. I used CTE to make is more readable.
WITH
CTE_Sum
AS
(
SELECT
Batting.playerID
,SUM(Batting.HR) AS TotalHR_Src
FROM
Batting
GROUP BY
Batting.playerID
)
,CTE_Update
AS
(
SELECT
People.playerID
,People.Total_HR
,CTE_Sum.TotalHR_Src
FROM
CTE_Sum
INNER JOIN People ON People.playerID = CTE_Sum.playerID
)
UPDATE CTE_Update
SET
Total_HR = TotalHR_Src
;

SQL: How to INSERT INTO with a value from another table and an Integer

I am trying to insert into 3 columns. The first columns needs an entry from another table, the second columns just needs a value and the third is NULL. So far I have this:
INSERT INTO PAT_CARAC ( NO_PATIENT, NO_CARACTE, DATEEXPIRA)
SELECT pp.NO_PATIENT,'16', NULL
FROM PAT_PATIENT pp
INNER JOIN PAT_CARAC pc ON pp.NO_PATIENT = pc.NO_PATIENT
WHERE pp.NO_CLINIQUE = 2;
I keep getting a PRIMARY or UNIQUE KEY constraint. Any help would be very much appreciated. Thanks!
Most probably your PAT_CARAC.NO_PATIENT field is primary key and your query is generating duplicate values
although you can try
INSERT INTO PAT_CARAC ( NO_PATIENT, NO_CARACTE, DATEEXPIRA)
SELECT DISTINCT pp.NO_PATIENT,'16', NULL
FROM PAT_PATIENT pp INNER JOIN PAT_CARAC pc ON pp.NO_PATIENT = pc.NO_PATIENT WHERE pp.NO_CLINIQUE = 2;

SQL insert data into a table from another table

I'm having a problem trying to insert some values into a table. I made an empty table with the fields
id(primary key)
association_id
resource_id
I have another table with
resource_id
association_id
and another one with
id(coresponding to the association_id in the former one)
image
I want to insert the resource_id and association_id from the first populated table, where the image field of the coresponding id from the last table is not empty.
I tried this:
INSERT IGNORE INTO `logo_associations` (``,`association_id`,`resource_id`)
SELECT
``,
`a`.`association_id`,
`a`.`resource_id`
FROM doc24_associations_have_resources a
Join doc24_associations An on a.association_id = An.id
WHERE An.image<>''
but it does not work
Try this:
INSERT INTO logo_associations (association_id, resource_id)
SELECT a.association_id
,a.resource_id
FROM doc24_associations_have_resources a
LEFT JOIN doc24_associations an ON a.association_id = an.id
WHERE an.image IS NULL -- check for null with left join
This is valid for SQL Server. You do not need to select and insert the first column as it is an identity as you mention.
My experience is based on SQL Server but the SQL may be very similar
INSERT INTO DestinationTable
(association_id, resource_id)
SELECT LNK.assocication_id,
LNK.resource_id
FROM LinkTable AS LNK
INNER JOIN ImageTable AS IMG ON IMG.id = LNK.association_id
AND IMG.image IS NOT NULL
Above I assume the following:
Tables are named DestinationTable, LinkTable, and ImageTable respectively
In DestinationTable the primary key (id) is auto generated

SQL query that merges two tables together with a where clause

Hi I want to search through table 2 with a value (names CustID) from table 1, and if all the values are found in table 2 (CustID) that matches table 1 (CustID) the values must be shown together with all the values from table 1 that does not match table 2's values.
Is it possible to do it this way and if it is can you please show me how, I need this for a project.
Thanks in advance
It sounds like you want a "LEFT" JOIN, which will pull up all records in table1 plus the matching ones in table2.
SELECT A.,B. FROM table1 A LEFT JOIN table2 B ON A.CustID = B.CustID