so for this, the goal is to add a column to a table called ENROLLMENT called FullFeePaid and to populate the column (assuming its null) but the only two possible answers can be Yes or No comparing data from another table called Course.
So I type the following command using alter however I keep getting a message where there's a duplicate, even i've never made a column called FullFeePaid.
But before that I kept getting an error saying there's a syntax error where it says
"set e.FullPaid = if(c.fee - e.amount <= 0 'yes', 'no')".
SET SQL_SAFE_UPDATES = 0;
ALTER TABLE enrollment
add fullfeepaid varchar(45) NULL;
UPDATE ENROLLMENT as e
JOIN COURSE as c on e.CourseNumber = c.CourseNumber
set e.FullFeePaid = if(c.fee - e.amountpaid <= 0 'yes', 'no')
where e.CourseNumber = c.CourseNumber;
select *
from enrollment;
You're missing a comma between the condition and the result your want to return if it evaluates as true:
UPDATE ENROLLMENT as e
JOIN COURSE as c on e.CourseNumber = c.CourseNumber
SET e.FullFeePaid = if(c.fee - e.amountpaid <= 0, 'yes', 'no')
-- Missing comma in the OP ---------------------^
WHERE e.CourseNumber = c.CourseNumber;
Related
I have the following code table A has a check constraint on column Denial.
CREATE TABLE Table a
(
[ID] int IDENTITY(1,1) NOT NULL ,
[EntityID] int ,
Denial nVarchar(20)
CONSTRAINT Chk_Denial CHECK (Denial IN ('Y', 'N')),
)
Merge statement
MERGE INTO Table a WITH (HOLDLOCK) AS tgt
USING (SELECT DISTINCT
JSON_VALUE(DocumentJSON, '$.EntityID') AS EntityID,
JSON_VALUE(DocumentJSON, '$.Denial') AS Denial
FROM Table1 bd
INNER JOIN table2 bf ON bf.FileUID = bd.FileUID
WHERE bf.Type = 'Payment') AS src ON tgt.[ID] = src.[ID]
WHEN MATCHED
)) THEN
UPDATE SET tgt.ID = src.ID,
tgt.EntityID = src.EntityID,
tgt.Denial = src.Denial,
WHEN NOT MATCHED BY TARGET
THEN INSERT (ID, EntityID, Denial)
VALUES (src.ID, src.EntityID, src.Denial)
THEN DELETE
I get this error when running my MERGE statement:
Error Message Msg 547, Level 16, State 0, Procedure storproctest1, Line 40 [Batch Start Line 0]
The MERGE statement conflicted with the CHECK constraint "Chk_Column". The conflict occurred in the database "Test", table "Table1", and column 'Denial'. The statement has been terminated.
This is due to the source files having "Yes" and "No" instead of 'Y' and 'N'. Hence, I'm getting the above error.
How can I use a Case statement in merge statement to handle the above Check constraints error? or Any alternative solutions.
You can turn Yes to Y and No to N before merging your data. That would belong to the using clause of the merge query:
USING (
SELECT Distinct
JSON_VALUE(DocumentJSON, '$.EntityID') AS EntityID,
CASE JSON_VALUE(DocumentJSON, '$.Denial')
WHEN 'Yes' THEN 'Y'
WHEN 'No' THEN 'N'
ELSE JSON_VALUE(DocumentJSON, '$.Denial')
END AS Denial
FROM Table1 bd
INNER JOIN table2 bf ON bf.FileUID = bd.FileUID
WHERE bf.Type = 'Payment'
) AS src
The case expression translates Y and N values, and leaves other values untouched. Since this applies to the source dataset, the whole rest of the query benefits (ie both the update and insert branches).
I have a sql query (below) to insert records into a database. The goal is to insert only new / unique entries in the database. So it will insert the row if the row doesn't already exist in the entire database. I would like to have it evaluate that row against ONLY the rows that have the symbol in the instrumentSymbol, rather than evaluating against every row in the entire database.
I am running into this syntax error which I have pinpointed to be due to the use of an alias in line SELECT 1 FROM instrumentsHistory WHERE instrumentSymbol = 'ZYME' AS f
This query works fine if removing the WHERE instrumentSymbol = {SYMBOL} conditional, but I need to this to refine the set of records the query compares itself to (thus reducing time to complete task.
I have looked through the documentation which leads me to believe there is nothing wrong with this query. Can someone pls point me in the right direction?
The Error:
(sqlite3.OperationalError) near "AS": syntax error
[SQL: INSERT INTO instrumentsHistory (datetime, instrumentSymbol, observation, observationColName)
SELECT t.datetime, t.instrumentSymbol, t.observation, t.observationColName
FROM tempTable t
WHERE NOT EXISTS
(SELECT 1 FROM instrumentsHistory WHERE instrumentSymbol = 'ZYME' AS f
WHERE t.datetime = f.datetime
AND t.instrumentSymbol = f.instrumentSymbol
AND t.observation = f.observation
AND t.observationColName = f.observationColName)]
EDIT 1:
Adding complete query...
sql = f"""INSERT INTO instrumentsHistory (datetime, instrumentSymbol, observation, observationColName)
SELECT t.datetime, t.instrumentSymbol, t.observation, t.observationColName
FROM tempTable t
WHERE NOT EXISTS
(SELECT 1 FROM instrumentsHistory WHERE instrumentSymbol = '{symbol}' AS f
WHERE t.datetime = f.datetime
AND t.instrumentSymbol = f.instrumentSymbol
AND t.observation = f.observation
AND t.observationColName = f.observationColName)"""
This code:
WHERE NOT EXISTS (SELECT 1 FROM instrumentsHistory WHERE instrumentSymbol = 'ZYME' AS f
WHERE t.datetime = f.datetime
has multiple errors. There are two WHERE clauses in a row. And as is being used in a WHERE clause. I am guessing this is a copy-and-past error, but it is unclear what you intend.
I am using an Insert trigger on a table where I copy one record from one table to another.
Everything is ok. It works fine except on datetime columns. When I add a datetime column into the inserted values, then I get an error:
Invalid column name
My code is
ALTER TRIGGER [dbo].[Insert_MoinitoringBasic]
ON [dbo].[M0_BasicInfo]
FOR INSERT
AS
BEGIN
MERGE [MonitoringROSCII].[dbo].[MonitorBasicInfo] AS d
USING (SELECT DistrictID, upazilaID, LC_ID, AcademicYear, Trimester, RepID,
CASE VisitType
WHEN 'Initial validation' THEN 1
WHEN 'Full validation' THEN 2
WHEN 'Compliance monitoring' THEN 3
END AS VisitTp
FROM INSERTED) AS s ON s.DistrictID = d.DistrictID
AND s.upazilaID = d.upazilaID
AND s.LC_ID = d.LCID
AND s.AcademicYear = d.LCVisitYr
AND s.Trimester = d.Trimister
AND s.RepID = d.MOID
AND s.VisitTp = d.VisitType
WHEN MATCHED THEN
UPDATE
SET DistrictID = S.DistrictID
WHEN NOT MATCHED THEN
INSERT (DistrictID, UpazilaID, LCID, VisitType, LCVisitYr, Trimister, MOID,
LCStatus, IfCloseWhy, OthersSpecify,LC1stVstDt)
VALUES (DistrictID, UpazilaID, Lc_ID, VisitTp, AcademicYear, Trimester, RepId,
2, 'No', 'No', FirstVisitDate);
END
Here the last line FirstVisitDate which is a datetime column. Without this column, it worked nice but when I include this column, it shows the error mentioned above.
Can anybody help me with this?
Thanks
As the error text suggests, you are refering to a column that does not exist.
In the SELECT part of your MERGE statement, there is no output column named FirstVisitDate, which is why you're getting the error...
I have trouble with my query which I want to insert and update while it is duplicate, but it said "Invalid use of group function" instead.
I have run my only "Select" statement and there was no issue like "Invalid use of group function".
here is my full code :
INSERT INTO tbl_biir_aktual(cabang_kode, periode_thn, periode_bln, pending_pp_volume, pending_pp_value)
SELECT a.cabang_kode, YEAR(a.tanggal) AS tahun, MONTH(a.tanggal)AS bulan,
SUM(a.qty_pending*a.unit_barang)AS tonase_pending, SUM(a.value_pending)AS value_pending
FROM tbl_order a,
(SELECT b.cabang_kode, MAX(b.tanggal)tanggal
FROM tbl_order b
GROUP BY b.cabang_kode, YEAR(b.tanggal), MONTH(b.tanggal)) AS max_cabang
WHERE max_cabang.cabang_kode = a.cabang_kode AND max_cabang.tanggal = a.tanggal
GROUP BY cabang_kode, YEAR(tanggal), MONTH(tanggal)
ON DUPLICATE KEY
UPDATE pending_pp_volume = SUM(a.qty_pending*a.unit_barang), pending_pp_value = SUM(a.value_pending);
well,
Hey I just found this MySQL ON DUPLICATE KEY UPDATE while inserting a result set from a query
INSERT INTO tbl_biir_aktual(cabang_kode, periode_thn, periode_bln, pending_pp_volume, pending_pp_value)
SELECT a.cabang_kode, YEAR(a.tanggal) AS tahun, MONTH(a.tanggal)AS bulan,
#tonase_pending := SUM(a.qty_pending*a.unit_barang)AS tonase_pending, #value_pending := SUM(a.value_pending)AS value_pending
FROM tbl_order a,
(SELECT b.cabang_kode, MAX(b.tanggal)tanggal
FROM tbl_order b
GROUP BY b.cabang_kode, YEAR(b.tanggal), MONTH(b.tanggal)) AS max_cabang
WHERE max_cabang.cabang_kode = a.cabang_kode AND max_cabang.tanggal = a.tanggal
GROUP BY cabang_kode, YEAR(tanggal), MONTH(tanggal)
ON DUPLICATE KEY
UPDATE pending_pp_volume = #tonase_pending, pending_pp_value = #value_pending;
I've tried that and it's done.
Tq Edper for your comment anyway....
Try using the alias in your update:
UPDATE SET pending_pp_volume = tonase_pending, pending_pp_value = value_pending
Also it's more wise to use another name for your alias for your aggregate than using the same name as your existing field name like the value_pending. Might as well changed it to TotalValuePending, so that it would be:
UPDATE SET pending_pp_volume = tonase_pending, pending_pp_value = TotalValuePending
I need to fill some fields in a table getting informations from other records of the same table.
I tried to write a query to explain what I want to do:
update globale2
set
nita = t.nita,
tita = t.tita,
notaita = t.notaita
where
neng = t.neng and
nita is null
(select nita, neng, tita, notaita from globale where uris='mma' and nita is not null) as t
edit to eplain better:
every records have these fields: "nita", "tita", "notaita", "neng" ("neng" cannot be null)
I want to fill these fields: "nita", "tita", "notaita" (where "nita" is empty)
with the same values from another record where "neng" equals the other "neng"
You can however, join the two tables.
UPDATE globale2 g
INNER JOIN globale gg
ON g.neng = gg.neng
SET g.nita = gg.nita,
g.tita = gg.tita,
g.notaita = gg.notaita
WHERE g.nita IS NULL
AND gg.uris = 'mma'
AND gg.nita IS NOT NULL
assume there is a table A_temp, with two columns 'one' and 'two'.
TABLE A_temp
ONE TWO
1 2
this is the present status of the table.
The query
UPDATE (SELECT * FROM A_temp ) A SET one = A.two where one = '1'
updates the table as
ONE TWO
2 2
Hope you get the idea and that it helps..