Postgresql: deleting duplicate records by CompanyID and CustomerID - postgresql

I can't get the following query to work. It will work if I remove the last line of the query. Any suggestions are greatly appreciated.
DELETE FROM "ProjectMaster"
USING "ProjectMaster" ua2
WHERE "ProjectMaster"."EngagementName" = ua2."EngagementName"
AND "ProjectMaster"."ProjectMasterID" < ua2."ProjectMasterID"
AND "CompanyID" = 490 and "ClientID" = 11125

When I run your query in a fiddle, it gives me :
error: relation "ProjectMaster" does not exist
Here are a few changes that can be done to avoid this error, without altering the logic (that you did not actually explain) :
alias the table that you insert to (ua1)
prefix the fields in the last line with the table they belong to (ua1 or ua2 ?)
get rid of these noisy quotes
This runs without syntax error :
DELETE FROM ProjectMaster ua1
USING ProjectMaster ua2
WHERE
ua1.EngagementName = ua2.EngagementName
AND ua1.ClientID = ua2.ClientID
AND ua1.ProjectMasterID < ua2.ProjectMasterID
AND ua1.CompanyID = 490 and ua1.ClientID = 11125;

I'm thinking something like this:
DELETE FROM "ProjectMaster"
WHERE "CompanyID" = 490 and "ClientID" = 11125 AND
"ProjectMasterID" < (SELECT MAX(pm2."ProjectMasterID"
FROM "ProjectMaster" pm2
WHERE pm2."CompanyID" = "ProjectMaster"."CompanyID" AND
pm2."ClientID" = "ProjectMaster"."ClientID"
);
That is, the correlation is to the company and client, not to something called engagement. This is based on my interpretation of the title of your question.

Related

SELECT with substring in ON clause?

I have the following select statement in ABAP:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
INTO corresponding fields of table GT_INSTMUNIC_F
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN EVER AS EV on
MUNIC~POD = EV~VREFER(9).
"where EV~BSTATUS = '14' or EV~BSTATUS = '32'.
My problem with the above statement is that does not recognize the substring/offset operation on the 'ON' clause. If i remove the '(9) then
it recognizes the field, otherwise it gives error:
Field ev~refer is unknown. It is neither in one of the specified tables
nor defined by a "DATA" statement. I have also tried doing something similar in the 'Where' clause, receiving a similar error:
LOOP AT gt_instmunic.
clear wa_gt_instmunic_f.
wa_gt_instmunic_f-mandt = gt_instmunic-mandt.
wa_gt_instmunic_f-bis = gt_instmunic-bis.
wa_gt_instmunic_f-ab = gt_instmunic-ab.
wa_gt_instmunic_f-zzelecdate = gt_instmunic-zzelecdate.
wa_gt_instmunic_f-ZZCERTDATE = gt_instmunic-ZZCERTDATE.
wa_gt_instmunic_f-CONSYEAR = gt_instmunic-CONSYEAR.
wa_gt_instmunic_f-ZDIMO = gt_instmunic-ZDIMO.
wa_gt_instmunic_f-ZZONE_M = gt_instmunic-ZZONE_M.
wa_gt_instmunic_f-ZZONE_T = gt_instmunic-ZZONE_T.
wa_gt_instmunic_f-USAGE_M = gt_instmunic-USAGE_M.
wa_gt_instmunic_f-USAGE_T = gt_instmunic-USAGE_T.
temp_pod = gt_instmunic-pod.
SELECT vrefer
FROM ever
INTO wa_gt_instmunic_f-vrefer
WHERE ( vrefer(9) LIKE temp_pod ). " PROBLEM WITH SUBSTRING
"AND ( BSTATUS = '14' OR BSTATUS = '32' ).
ENDSELECT.
WRITE: / sy-dbcnt.
WRITE: / 'wa is: ', wa_gt_instmunic_f.
WRITE: / 'wa-ever is: ', wa_gt_instmunic_f-vrefer.
APPEND wa_gt_instmunic_f TO gt_instmunic_f.
WRITE: / wa_gt_instmunic_f-vrefer.
ENDLOOP.
itab_size = lines( gt_instmunic_f ).
WRITE: / 'Internal table populated with', itab_size, ' lines'.
The basic task i want to implement is to modify a specific field on one table,
pulling values from another. They have a common field ( pod = vrefer(9) ). Thanks in advance for your time.
If you are on a late enough NetWeaver version, it works on 7.51, you can use the OpenSQL function LEFT or SUBSTRING. Your query would look something like:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN ever AS ev
ON MUNIC~POD EQ LEFT( EV~VREFER, 9 )
INTO corresponding fields of table GT_INSTMUNIC_F.
Note that the INTO clause needs to move to the end of the command as well.
field(9) is a subset operation that is processed by the ABAP environment and can not be translated into a database-level SQL statement (at least not at the moment, but I'd be surprised if it ever will be). Your best bet is either to select the datasets separately and merge them manually (if both are approximately equally large) or pre-select one and use a FAE/IN clause.
They have a common field ( pod = vrefer(9) )
This is a wrong assumption, because they both are not fields, but a field an other thing.
If you really need to do that task through SQL, I'll suggest you to check native SQL sentences like SUBSTRING and check if you can manage to use them within an EXEC_SQL or (better) the CL_SQL* classes.

no viable alternative at input 'is false'

trying to query database in aws athena but got this error:
WHERE
"fo0"."date" > date'2014-08-03'
AND "re0"."rating" IS NOT NULL
AND "fi0"."is_side" is FALSE
GROUP BY "Name"
HAVING COUNT(DISTINCT "re0"."id") > 10
ORDER BY "% More Loves than Dislikes" DESC
;
I am pretty new to athena. Any resolve is helpful.
It looks like you may need to change this line:
AND "fi0"."is_side" is FALSE
to:
AND "fi0"."is_side" = FALSE
Since it sounds like your is_side datatype is a tinyint, try the following:
ND "fi0"."is_side" = 0

how can one table name used more than once in query of postgresql

I create view in the postgresql that for write query but error message display table name used more than once. How to solve this problem?
Query
SELECT
tbcitizen.firstname || '-' || tbcitizen.middlename || '-' || tbcitizen.familyname as firstname,
tbcitizen.dateofbirth,
tbcity.cityname,
tbcontact.contactdetails,
tbcitizen.citizenidp
FROM
public.tbcitizen,
public.tbaddress,
public.tbcity,
public.tbcontact
INNER JOIN
tbcontact ON tbcitizen.citizenidp = tbcontact.referenceidf AND tbcontact.referencetypeidf = 1 AND
tbcontact.isprimery = 1 INNER JOIN
tbaddress ON tbcitizen.citizenidf = tbaddress.referenceidf AND tbaddress.referencetypeidf = 1 AND
tbaddress.isprimery = 1 INNER JOIN
tbcity ON tbaddress.cityidf = tbcity.cityidp
WHERE
tbaddress.referencetypeidf = tbcitizen.citizenidp AND
tbaddress.referenceidf = tbcitizen.citizenidp AND
tbaddress.cityidf = tbcity.cityidp
Error = table name "tbcontact" specified more than once
Thanks
As the error states that - your table tbcontact used 2 times as the source table. So it creates ambiguity for the postgres database engine. So to resolve this issue you have to use table alias with different name.
Hope it'll help you.

Metadata about a column in SQL Server 2008 R2?

I'm trying to figure out a way to store metadata about a column without repeating myself.
I'm currently working on a generic dimension loading SSIS package that will handle all my dimensions. It currently does :
Create a temporary table identical to the given table name in parameters (this is a generic stored procedure that receive the table name as parameter, and then do : select top 0 * into ##[INSERT ORIGINAL TABLE NAME HERE] from [INSERT ORIGINAL TABLE NAME HERE]).
==> Here we insert custom code for this particular dimension that will first query the data from a datasource and get my delta, then transform the data and finally loads it into my temporary table.
Merge the temporary table into my original table with a T-SQL MERGE, taking care of type1 and type2 fields accordingly.
My problem right now is that I have to maintain a table with all the fields in it to store a metadata to tell my scripts if this particular field is type1 or type2... this is nonsense, I can get the same data (minus type1/type2) from sys.columns/sys.types.
I was ultimately thinking about renaming my fields to include their type in it, such as :
FirstName_T2, LastName_T2, Sex_T1 (well, I know this can be type2, let's not fall into that debate here).
What do you guyz would do with that? My solution (using a table with that metadata) is currently in place and working, but it's obvious that repeating myself from the systables to a custom table is nonsense, just for a simple type1/type2 info.
UPDATE: I also thought about creating user defined types like varchar => t1_varchar, t2_varchar, etc. This sounds like something a bit sluggy too...
Everything you need should already be in INFORMATION_SCHEMA.COLUMNS
I can't follow your thinking of not using provided tables/views...
Edit: As scarpacci mentioned, this somewhat portable if needed.
I know this is bad, but I will post an answer to my own question... Thanks to GBN for the help tho!
I am now storing "flags" in the "description" field of my columns. I, for example, can store a flag this way : "TYPE_2_DATA".
Then, I use this query to get the flag back for each and every column :
select columns.name as [column_name]
,types.name as [type_name]
,extended_properties.value as [column_flags]
from sys.columns
inner join sys.types
on columns.system_type_id = types.system_type_id
left join sys.extended_properties
on extended_properties.major_id = columns.object_id
and extended_properties.minor_id = columns.column_id
and extended_properties.name = 'MS_Description'
where object_id = ( select id from sys.sysobjects where name = 'DimDivision' )
and is_identity = 0
order by column_id
Now I can store metadata about columns without having to create a separate table. I use what's already in place and I don't repeat myself. I'm not sure this is the best possible solution yet, but it works and is far better than duplicating information.
In the future, I will be able to use this field to store more metadata, where as : "TYPE_2_DATA|ANOTHER_FLAG|ETC|OH BOY!".
UPDATE :
I now store the information in separate extended properties. You can manage extended properties using sp_addextendedproperty and sp_updateextendedproperty stored procedures. I have created a simple store procedure that help me to update those values regardless if they currently exist or not :
create procedure [dbo].[UpdateSCDType]
#tablename nvarchar(50),
#fieldname nvarchar(50),
#scdtype char(1),
#dbschema nvarchar(25) = 'dbo'
as
begin
declare #already_exists int;
if ( #scdtype = '1' or #scdtype = '2' )
begin
select #already_exists = count(1)
from sys.columns
inner join sys.extended_properties
on extended_properties.major_id = columns.object_id
and extended_properties.minor_id = columns.column_id
and extended_properties.name = 'ScdType'
where object_id = (select sysobjects.id from sys.sysobjects where sysobjects.name = #tablename)
and columns.name = #fieldname
if ( #already_exists = 0 )
begin
exec sys.sp_addextendedproperty
#name = N'Scd_Type',
#value = #scdtype,
#level0type = N'SCHEMA',
#level0name = #dbschema,
#level1type = N'TABLE',
#level1name = #tablename,
#level2type = N'COLUMN',
#level2name = #fieldname
end
else
begin
exec sys.sp_updateextendedproperty
#name = N'Scd_Type',
#value = #scdtype,
#level0type = N'SCHEMA',
#level0name = #dbschema,
#level1type = N'TABLE',
#level1name = #tablename,
#level2type = N'COLUMN',
#level2name = #fieldname
end
end
end
Thanks again

JPA Native Query delete in

I try to delete a list of rows from a table using this Native Query:
#NamedNativeQuery(name="WebGroup.DeleteIn",
query="DELETE FROM WebGroup WHERE
WebGroup.GROUP_ID IN (:IDsList)"
getEm().createNamedQuery("WebGroup.DeleteIn")
.setParameter("IDsList", groupToDeleteIDs)
.executeUpdate();
and this is the SQL that MySQL executes:
DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (:IDsList)
SO, JPA doesn't replace the variable IDsList...
Some one could help me please?
One way that works is if you not use the id value like you tried, but instead use the entity and let JPA handle the identification of it like this:
HashSet<Transaction> transactions = new HashSet<Transaction>();
...
entityManager.createQuery(
"DELETE FROM Transaction e WHERE e IN (:transactions)").
setParameter("transactions", new ArrayList<Transaction>(
transactions)).executeUpdate();
Hope it helps you in the right direction.
native queries do not support collection expansion neither named parameters.
you should write:
#NamedNativeQuery(name="WebGroup.DeleteIn", query="DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (?,?,?,?)"
Query query = getEm().createNamedQuery("WebGroup.DeleteIn");
for(int i = 0; i < 4; i++) query.setParameter(i + 1, groupToDeleteIDs.get(i));
query.executeUpdate();
but it is horrible
on eclipselink + mysql this one works:
#NamedNativeQuery(name="WebGroup.DeleteIn", query="DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (?)"
Query query = getEm().createNamedQuery("WebGroup.DeleteIn");
query.setParameter(1, StringUtils.join(groupToDeleteIDs, ",");
query.executeUpdate();
however it is not very nice...
but there isn't any other solution using a named query.