Insert in one table selecting form another base on condition - sql

Consider following relationship.
I am trying to add new row in Tenants from NewRentPayments if no Tenants's tuple found in NewRentPayments base on composite primary keys houseid and apartmentnumber.
Have a look in my query you will have better idea
insert into Tenants(houseid, apartmentnumber, leasetenantssn, leasestartdate, leaseexpirationdate, rent, lastrentpaiddate, rentoverdue)
(
select n.* from NewRentPayments as n left join Tenants as t
on
t.houseid = n.houseid
and
t.apartmentnumber = n.apartmentnumber
where
t.houseid is null
or
t.apartmentnumber is null
) as newval
(newval.houseid, newval.apartmentnumber, newval.leasetenantssn, now(), NULL, newval.rent, newval.datepaid, 'f');
It is giving error on as newval.
ERROR: syntax error at or near "as"
LINE 12: ) as newval
^
********** Error **********
ERROR: syntax error at or near "as"
SQL state: 42601
Character: 345
Note: This is not a simple insert value in one table from another table as done here. In my case I am inserting some constants/custom values too into the Tenants rows while inserting NewRentPayments tuples.
I am using Postgresql.

You need to put the values as you want to insert in a select.
Try this:
insert into Tenants (houseid, apartmentnumber, leasetenantssn, leasestartdate, leaseexpirationdate, rent, lastrentpaiddate, rentoverdue)
select newval.houseid, newval.apartmentnumber, newval.leasetenantssn, now(), null, newval.rent, newval.datepaid, 'f'
from (
select n.*
from NewRentPayments as n
left join Tenants as t on t.houseid = n.houseid
and t.apartmentnumber = n.apartmentnumber
where t.houseid is null
or t.apartmentnumber is null
) as newval;

Related

Query is giving me error message : The multi-part identifier "llpeople_tbl.Person_ecounsel" could not be bound

Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "llpeople_tbl.Person_ecounsel" could not be bound.
insert into [dbo].[Counsellor]
(
[TenantId], [EmployeeId])
select 1, [Id]
from [Employee] where llpeople_tbl.Person_ecounsel = 1
Cause :
This error usually occurs when an alias is used when referencing a column in a SELECT statement and the alias used is not defined anywhere in the FROM clause of the SELECT statement.
if the column Person_ecounsel is from table Employee, you either give the alias llpeople_tbl to Employee table or remove it as shown below.
insert into [dbo].[Counsellor]
(
[TenantId], [EmployeeId])
select 1, [Id]
from [Employee] where Person_ecounsel = 1
if the column Person_ecounsel is from different table, you should join that table (llpeople_tbl) accordingly.
I think you are missing a JOIN or a connection between the tables. I can speculate that you want something like this:
insert into [dbo].[Counsellor ([TenantId], [EmployeeId])
select 1, e.[Id]
from [Employee] e
where exists (select 1
from llpeople_tbl t
where t.person_id = e.person_id and
t.Person_ecounsel = 1
);
I am speculating that a column such as person_id is used to connect the tables.

INSERT a SELECT GROUP BY : more target columns than expressions error [duplicate]

This question already has an answer here:
PostgreSQL, SQL state: 42601
(1 answer)
Closed 3 years ago.
I have a query, that I want to make, it is an INSERT FROM a SELECT GROUP BY, but I get the error:
ERROR: INSERT has more target columns than expressions
LINE 15: INSERT INTO "KPI_MEASURE" (id, created_at, kpi_project_id, k...
_____________________________________^
HINT: The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?
I've searched this error, but what I found is that, this error happen, if the number of rows doesn't match, but for the query below, there is the same number of row.
Postgres SQL query:
INSERT INTO "KPI_MEASURE" (
id,
created_at,
kpi_project_id,
kpi_frequency_id,
kpi_metric_id,
branch,
value
)
SELECT (
nextval('"KPI_MEASURE_ID_seq"'::regclass),
now(),
kpi_project.id,
kpi_measure.kpi_frequency_id,
kpi_metric.id ,
kpi_measure.branch ,
sum(kpi_measure.value)
)
FROM "KPI_MEASURE" kpi_measure
INNER JOIN "KPI_METRIC" kpi_metric ON kpi_measure.kpi_metric_id = kpi_metric.id
INNER JOIN "KPI_PROJECT" kpi_project ON kpi_measure.kpi_project_id = kpi_project.id
INNER JOIN "KPI_AGGREGATION_PROJECT" kpi_agg_project ON kpi_project.name = kpi_agg_project.child_project_name
WHERE kpi_metric.aggregated = false
GROUP BY kpi_measure.branch, kpi_metric.id, kpi_project.id, kpi_project.name, kpi_frequency_id;
When you enclose expressions in parentheses, Postgres interprets the result as a tuple -- essentially a struct or record.
So, your statement:
SELECT (
nextval('"KPI_MEASURE_ID_seq"'::regclass),
now(),
kpi_project.id,
kpi_measure.kpi_frequency_id,
kpi_metric.id ,
kpi_measure.branch ,
sum(kpi_measure.value)
)
is returning one value. That value is a record.
Databases that do not support tuples would return an error.
The solution is to remove the parentheses.
As the hint says: Did you accidentally use extra parentheses?
Remove the parentheses around the selected values and the problem is solved.
INSERT INTO "KPI_MEASURE" (
id,
created_at,
kpi_project_id,
kpi_frequency_id,
kpi_metric_id,
branch,
value
)
SELECT
nextval('"KPI_MEASURE_ID_seq"'::regclass),
now(),
kpi_project.id,
kpi_measure.kpi_frequency_id,
kpi_metric.id ,
kpi_measure.branch ,
sum(kpi_measure.value)
FROM "KPI_MEASURE" kpi_measure
INNER JOIN "KPI_METRIC" kpi_metric ON kpi_measure.kpi_metric_id = kpi_metric.id
INNER JOIN "KPI_PROJECT" kpi_project ON kpi_measure.kpi_project_id = kpi_project.id
INNER JOIN "KPI_AGGREGATION_PROJECT" kpi_agg_project ON kpi_project.name = kpi_agg_project.child_project_name
WHERE kpi_metric.aggregated = false
GROUP BY kpi_measure.branch, kpi_metric.id, kpi_project.id, kpi_project.name, kpi_frequency_id;

I am trying to execute the following query, but it always reports an error

Schema
Tenants (HouseID, ApartmentNumber, LeaseTenantSSN, LeaseStartDate(not null), LeaseExpirationDate(can be null),
Rent, LastRentPaidDate, RentOverdue)
NewRentPayments (HouseID, ApartmentNumber, LeaseTenantSSN(not null), Rent(can be null), DatePaid)
Query
INSERT INTO Tenants (x.HouseID,x.ApartmentNumber,x.LeaseTenantSSN,CURRENT_DATE,NULL,x.Rent,x.Rent,FALSE)
SELECT x.HouseID, x.ApartmentNumber,x.LeaseTenantSSN,CURRENT_DATE,NULL,x.Rent,x.Rent
FROM NewRentPayments x
WHERE x.HouseID NOT IN (select HouseID
FROM Tenants)
OR x.ApartmentNumber NOT IN (SELECT ApartmentNumber
FROM Tenants
WHERE Tenants.HouseID=x.HouseID);
I always get an error on CURRENT_DATE,NULL.It says sintax error at or near CURRENT_DATE
Your syntax is off. Following INSERT INTO should be a list of column names into which you plan on inserting data, using the following SELECT as the source. Something like this should work:
INSERT INTO Tenants (HouseID, ApartmentNumber, LeaseTenantSSN, LeaseStartDate,
LeaseExpirationDate, Rent, LastRentPaidDate, RentOverdue)
SELECT x.HouseID, x.ApartmentNumber, x.LeaseTenantSSN, CURRENT_DATE, NULL, x.Rent,
x.DatePaid, FALSE
FROM NewRentPayments x
WHERE x.HouseID NOT IN (SELECT HouseID FROM Tenants) OR
x.ApartmentNumber NOT IN (SELECT ApartmentNumber FROM Tenants
WHERE Tenants.HouseID=x.HouseID);
I selected FALSE for the RentOverdue value, which seems to agree with your logic.
INSERT INTO requires the name of the columns in the which the given data must be inserted, after the table name. Obviously, CURRENT_DATE and NULL are not the name of the columns.

sql Error Code: 1241. Operand should contain 1 column(s)

it had been a while since i used sql,
need a little push...
got 2 table, users and votes
users {id,email....}
votes {id,userid,date,vote}
the sql:
INSERT INTO votes_table (users_table.id , date,vote)
VALUES (
(SELECT users_table.id, users_table.email
FROM users_table
WHERE users_table.email='lalala#lalall.com')
,datetime
,true
)
the error
Error Code: 1241. Operand should contain 1 column(s)
Your inner query is selecting 2 columns. Change this to just return the id:
INSERT INTO votes_table (users_table.id , date,vote)
VALUES (
(SELECT users_table.id
FROM users_table
WHERE users_table.email='lalala#lalall.com')
,datetime
,true
)
Try this, you are returning more number of columns in your sub-query, you can simply your query to this
INSERT INTO votes_table (users_table.id , date,vote)
SELECT users_table.id,datetime, true
FROM users_table
WHERE users_table.email='lalala#lalall.com'

Inserting into SQL Server from select

I'm trying try to insert rows from my select statement. But I get a syntax error at the first FROM in the statement. What am I doing wrong?
INSERT INTO [dbo].[OrganizationControlGroup]
VALUES
(
OrganizationId,
9999,
NULL,
CONVERT(DATE,SYSDATETIME()),
NULL,
CONVERT(DATE,SYSDATETIME())
)
FROM
(
SELECT TOP 450 o.OrganizationId
FROM Organization o
WHERE NOT EXISTS
(
SELECT *
FROM OrganizationControlGroup c
WHERE c.OrganizationId = o.OrganizationId
)
)
Your syntax is wrong. You can use INSERT either with VALUES and one (or in newer SQL Server versions more) single record expression list enclosed in parentheses, or with SELECT. If you use the SELECT variant, note that some column expressions can be constants or expressions like your CONVERT(DATE,SYSDATETIME()) that do not depend on the source table. The correct version of your statement would be:
INSERT INTO [dbo].[OrganizationControlGroup]
SELECT TOP 450
o.OrganizationId,
9999,
NULL,
CONVERT(DATE,SYSDATETIME()),
NULL,
CONVERT(DATE,SYSDATETIME())
FROM Organization o
WHERE NOT EXISTS
(
SELECT *
FROM OrganizationControlGroup c
WHERE c.OrganizationId = o.OrganizationId
)
The documentation for INSERT is here: http://msdn.microsoft.com/en-us/library/ms174335.aspx