How to insert data with select query in postgresql? - postgresql

How to insert data with select query sum? I tried. The result is affected success > Affected rows: 1. but row no add in the table.
CREATE TABLE Clases(Segment1_ID char(4), Segment1_Name varchar(75), CompanyID char(4), amount Float(53));
INSERT INTO Clases (Segment1_ID, Segment1_Name, CompanyID, amount)
select Segment1_ID, Segment1_Name, dataupload1h_companyid CompanyID, sum(case when Segment3_Formula = '+' then dataupload1d_amount else dataupload1d_amount * -1 end) Amount
from t_dataupload1_header
inner join t_dataupload1_detail
on dataupload1h_id = dataupload1d_id
inner join M_Account
on dataupload1d_accountid = Account_ID
and dataupload1h_companyid = Account_CompanyID
inner join M_Segment4
on Account_Segment4ID = Segment4_ID
and dataupload1h_companyid = Segment4_CompanyID
inner join M_Segment3
on Segment4_Segment3ID = Segment3_ID
and dataupload1h_companyid = Segment3_CompanyID
inner join M_Segment2
on Segment3_Segment2ID = Segment2_ID
and dataupload1h_companyid = Segment2_CompanyID
inner join M_Segment1
on Segment2_Segment1ID = Segment1_ID
and dataupload1h_companyid = Segment1_CompanyID
where dataupload1h_companyid = '1000'
group by Segment1_ID, Segment1_Name, dataupload1h_companyid
order by Segment1_ID, Segment1_Name, dataupload1h_companyid;
Please help. Thank you

If the select is returning the desired results then check whether Auto-commit is turned on in PgAdmin(I suppose you are using this) Or put COMMIT; after the insert.

Related

How can I use value from main select in Left Outer Join select - T-SQL

In my below T-SQL Query I need to use EFP_MessageCenter.MessageSender from my main SELECT in the SELECT in my LEFT OUTER JOIN as the value where I have placed <MessageSenderInitials>.
When I set (EFP_MessageCenter_1.MessageSender = EFP_MessageCenter.MessageSender) or (EFP_MessageCenter_1.MessageSender = MessageSenderInitials) I get the error The multi-part identifier "EFP_MessageCenter.MessageSender" could not be bound.
How can I get this to work?
SELECT LOWER(EFP_MessageCenter.MessageSender) AS MessageSenderInitials
, MAX(SenderInfo.FullName) AS SenderFullName
, MAX(SenderInfo.ProfilePicture) AS SenderProfilePicture
, MAX(EFP_MessageCenter_Receiver.UserID) AS ReceiverID
, MAX(EFP_MessageCenter.MessageTimestamp) AS ChangeDate
, COUNT(DisplayCountSelect.Displayed) AS CountNonReadMessages
FROM EFP_MessageCenter_Receiver
INNER JOIN EFP_MessageCenter ON EFP_MessageCenter_Receiver.MessageID = EFP_MessageCenter.id
INNER JOIN EFP_EmploymentUser AS SenderInfo ON EFP_MessageCenter.MessageSender = SenderInfo.Initials
LEFT OUTER JOIN
(SELECT EFP_MessageCenter_Receiver_1.Displayed, EFP_MessageCenter_Receiver_1.UserID, EFP_MessageCenter_1.MessageSender
FROM EFP_MessageCenter AS EFP_MessageCenter_1
INNER JOIN EFP_MessageCenter_Receiver AS EFP_MessageCenter_Receiver_1 ON EFP_MessageCenter_1.id = EFP_MessageCenter_Receiver_1.MessageID
WHERE (EFP_MessageCenter_Receiver_1.Displayed = 0) AND (EFP_MessageCenter_Receiver_1.UserID = 65) AND (EFP_MessageCenter_1.MessageSender = '<MessageSenderInitials>'))
AS DisplayCountSelect
ON DisplayCountSelect.UserID = EFP_MessageCenter_Receiver.UserID
WHERE (EFP_MessageCenter_Receiver.UserID = 65) AND (EFP_MessageCenter.MessageType = 'SPECIFIC')
GROUP BY EFP_MessageCenter.MessageSender
ORDER BY ChangeDate DESC
I've made a slight refactor of your query and changed the outer join to an an outer apply
It's not going to be 100% working I'm sure but should allow you to tweak it and include the correlation you need to.
I suspect you could move the CountNonReadMessages to a count(*) in the apply and possibly remove the aggregation, but that's just a guess.
select Lower(mc.MessageSender) as MessageSenderInitials
, Max(s.FullName) as SenderFullName
, Max(s.ProfilePicture) as SenderProfilePicture
, Max(mr.UserID) as ReceiverID
, Max(mc.MessageTimestamp) as ChangeDate
, Count(s.Displayed) as CountNonReadMessages
from EFP_MessageCenter_Receiver mr
join EFP_MessageCenter mc on mr.MessageID = mc.id
join EFP_EmploymentUser eu on mc.MessageSender = eu.Initials
outer apply (
select mr.Displayed
from EFP_MessageCenter mcx
join EFP_MessageCenter_Receiver mrx on mcx.id = mrx.MessageID
where mrx.Displayed = 0
and mrx.UserId=mr.UserId
and mcx.UserID = 65 /* this should probably be correlated */
and mcx.MessageSender = '<MessageSenderInitials>'
) s
where mr.UserID = 65 and mc.MessageType = 'SPECIFIC'
group by mc.MessageSender
order by ChangeDate desc

Need to convert Oracle "merge into" query to PostgreSQL

I'm trying to convert the following Oracle query to PostgreSQL:
MERGE into feepay.TRPT_W2_REPORTS TRPT1
USING(
WITH RWS AS
(SELECT PROG.BINCLIENT, TRPT.PUT_DIRECTORY
FROM feepay.program2 PROG
INNER JOIN feepay.TRPT_W2_PROGRAMS TRPT
ON (PROG.BINCLIENT = TRPT.BINCLIENT OR PROG.ISSUER_ID = TRPT.ISSUER_ID))
SELECT TCI.CUSTOMERNAME AS ACCOUNT,
TC.CUSTOMER_ID AS urn,
TC.LAST_NAME,
TC.FIRST_NAME,
TC.DOB,
TCA.ADDRESS
FROM feepay.TAU_CARDNUMBERS TCN
INNER JOIN feepay.TAU_CUSTOMER_CARDNUMBER TCCN ON (TCN.CARDNUMBER_ID = TCCN.CARDNUMBER_ID)
INNER JOIN feepay.TBLCUSTOMERS TC ON (TCCN.CUSTOMER_ID = TC.CUSTOMER_ID)
LEFT JOIN feepay.tau_customeraddress TCA ON (TC.CUSTOMER_ID = TCA.CUSTOMER_ID)
INNER JOIN feepay.TAU_ISSUER TI ON (TI.ISSUER_ID = TCN.ISSUER_ID)
INNER JOIN feepay.TBLCUSTOMERS TCI ON (TCI.CUSTOMER_ID = TI.CUSTOMER_ID)
LEFT JOIN feepay.TRPT_W2_REPORTS TRPT ON (TRPT.URN = TC.CUSTOMER_ID)
WHERE BINCLIENT IN (SELECT BINCLIENT FROM RWS)
AND TC.CUSTOMERNAME NOT IN ('freepay card','svds card')) TRPT2
ON (TRPT1.URN = TRPT2.URN)
WHEN MATCHED THEN
UPDATE SET
TRPT1.ACCOUNT = TRPT2.ACCOUNT,
TRPT1.LAST_NAME = TRPT2.LAST_NAME,
TRPT1.FIRST_NAME = TRPT2.FIRST_NAME,
TRPT1.DOB = TRPT2.DOB,
TRPT1.ADDRESS = TRPT2.ADDRESS,
TRPT1.LAST_UPDATE = now(),
TRPT1.STATUS = 'u' /* uPDATED */
WHEN NOT MATCHED THEN
INSERT (ACCOUNT, URN, LAST_NAME, FIRST_NAME, ISENTITY, DOB, ADDRESS, LAST_UPDATE, STATUS)
VALUES (TRPT2.ACCOUNT, TRPT2.URN, TRPT2.LAST_NAME, TRPT2.FIRST_NAME, 'y', TRPT2.DOB, TRPT2.MIDDLE_NAME,
TRPT2.ADDRESS, now(), 'i');
Unfortunately PostgreSQL does not support MERGE, so I'm really stuck. I hope some database pro out of here can help me with this.
You can use INSERT ON CONFLICT () instead:
insert into feepay.TRPT_W2_REPORTS (ACCOUNT, URN, LAST_NAME, FIRST_NAME, ISENTITY, DOB, ADDRESS, LAST_UPDATE, STATUS)
WITH RWS AS (
SELECT PROG.BINCLIENT, TRPT.PUT_DIRECTORY
FROM feepay.program2 PROG
INNER JOIN feepay.TRPT_W2_PROGRAMS TRPT
ON (PROG.BINCLIENT = TRPT.BINCLIENT OR PROG.ISSUER_ID = TRPT.ISSUER_ID)
)
SELECT TCI.CUSTOMERNAME,
TC.CUSTOMER_ID,
TC.LAST_NAME,
TC.FIRST_NAME,
'Y'
TC.DOB,
TCA.ADDRESS,
now(),
'i'
FROM feepay.TAU_CARDNUMBERS TCN
INNER JOIN feepay.TAU_CUSTOMER_CARDNUMBER TCCN ON (TCN.CARDNUMBER_ID = TCCN.CARDNUMBER_ID)
INNER JOIN feepay.TBLCUSTOMERS TC ON (TCCN.CUSTOMER_ID = TC.CUSTOMER_ID)
LEFT JOIN feepay.tau_customeraddress TCA ON (TC.CUSTOMER_ID = TCA.CUSTOMER_ID)
INNER JOIN feepay.TAU_ISSUER TI ON (TI.ISSUER_ID = TCN.ISSUER_ID)
INNER JOIN feepay.TBLCUSTOMERS TCI ON (TCI.CUSTOMER_ID = TI.CUSTOMER_ID)
LEFT JOIN feepay.TRPT_W2_REPORTS TRPT ON (TRPT.URN = TC.CUSTOMER_ID)
WHERE BINCLIENT IN (SELECT BINCLIENT FROM RWS)
AND TC.CUSTOMERNAME NOT IN ('freepay card','svds card')) TRPT2
ON CONFLICT (URN)
DO UPDATE SET
ACCOUNT = excluded.ACCOUNT,
LAST_NAME = excluded.LAST_NAME,
FIRST_NAME = excluded.FIRST_NAME,
DOB = excluded.DOB,
ADDRESS = excluded.ADDRESS,
LAST_UPDATE = now(),
STATUS = 'u' /* uPDATED */
You need to verify if the columns in the SELECT list match the columns as listed in the INSERT column list.

sql, group a query with no aggregations and multiple tables

I need to group the query below by dda.LA and need to display all the columns listed in the select but almost none of them are aggregated. i don't know what the syntax to get around this is and i can not find a post that shows this syntax (most examples only have one table, two at tops).
Select dda.a,
dda.b,
dda.c,
dda.d,
dda.e,
dda.f,
dda.g,
dda.h,
dda.i,
dda.j,
dda.k,
dda.l,
dda.m,
dda.n,
dda.o,
dda.p,
dda.r,
dda.u,
dda.LA,
dd.aa,
coalesce(apn.apn,Pt.z) as abc,
coalesce(apn.v,Pt.y) as def,
'RFN' RowFocusIndicator ,
'SRI' SelectRowIndicator ,
'Y' Expanded ,
Convert(Int, Null) SortColumn
From dda (NoLock)
Inner Join dd (NoLock) On dda.d = dd.q and dda.e = dd.e
Left Outer Join apn (nolock) on dda.r = apn.r
Left Outer Join Pt (nolock) on dda.s = Pt.t
Where 1 = 1
And dda.u = (Select Min(c.w)
From c (NoLock)
Where c.x = dda.s)
Thanks!
Just add this to any column that you want to aggregate by:
AggregatedColumnName = Aggregation(fieldToAggregate) Over (Partition By dda.LA)
ex.
aCount = Count(dda.a) Over (Partition By dda.LA)

Grades of each quiz in Moodle

I'm trying to get grades of each question, I have a query but it only return final grade of whole exam, but i want grade of each question, how to get it?
Here is query that i have:
SELECT mdl_grade_items.id AS ItemID,
mdl_course.shortname AS CourseShortname,
mdl_grade_items.itemname AS ItemName,
mdl_grade_items.grademax AS ItemGradeMax,
mdl_grade_items.aggregationcoef AS ItemAggregation,
mdl_grade_grades.finalgrade AS FinalGrade,
mdl_user.username AS StudentID,
mdl_user.id
FROM mdl_grade_items
INNER JOIN mdl_grade_grades
ON mdl_grade_items.id = mdl_grade_grades.itemid
INNER JOIN mdl_role_assignments
ON mdl_grade_grades.userid = mdl_role_assignments.userid
AND mdl_grade_items.courseid = mdl_role_assignments.mdlcourseid
INNER JOIN mdl_course
ON mdl_course.id = mdl_grade_items.courseid
INNER JOIN mdl_user
ON mdl_user.id = mdl_role_assignments.userid
Ok, i found it
SELECT mqa.id,meqi.grade * (select fraction from mdl_question_attempt_steps where
questionattemptid = mqas.questionattemptid and state like 'mangr%' order by id desc limit
1 ) finalgrade,me.course , mqas.userid,u.firstname, u.lastname, mqa.questionsummary,
mqa.responsesummary , meqi.grade
FROM mdl_question_attempts mqa
left JOIN mdl_question_attempt_steps mqas ON mqa.id = mqas.questionattemptid
left JOIN mdl_user u ON mqas.userid = u.id
left JOIN mdl_examm_question_instances meqi ON meqi.question = mqa.questionid
left JOIN mdl_examm me ON meqi.examm = me.id
WHERE me.course= $courseID and userid = $userID

query optimization

I have 50964218 records in a table. I am going to fetch the data from this table and insert into the same table. Which takes more time to manipulate. How optimize this query.
The Query is
INSERT INTO contacts_lists (contact_id, list_id, is_excluded, added_by_search)
SELECT contact_id, 68114 , TRUE, added_by_search
FROM contacts_lists cl1
WHERE list_id = 67579
AND is_excluded = TRUE
AND NOT EXISTS
(SELECT 1 FROM contacts_lists cl2
WHERE cl1.contact_id = cl2.contact_id AND cl2.list_id = 68114 )
index: list_id,contact_id
you will probably get better results with a left join:
select t1.[field], ...
from t1
left join t2
on [conditions]
where t2.[any pkey field] is null;