Query to find duplicate lows
Dear all,
i have a table
create table attendance(dept_id number,att_date date,att_kind);
all the three columns i want to put as a primary key,
there is a data in the table.
how would i check through a query that the table has duplicate values or not?
in other words , i want to query just the duplicate records so i delete them manually.
thanks & Regards
You do it like this.
SQL> select * from attendance;
DEPT_ID ATT_DATE ATT_KIND
100 20-FEB-10 1
100 20-FEB-10 1
200 20-FEB-10 1
200 20-FEB-10 2
SQL> create table exceptions(row_id rowid,
2 owner varchar2(30),
3 table_name varchar2(30),
4 constraint varchar2(30));
Table created.
SQL> alter table attendance add constraint att_pk primary key (dept_id, att_date, att_kind) exceptions into exceptions;
alter table attendance add constraint att_pk primary key (dept_id, att_date, att_kind) exceptions into exceptions
ERROR at line 1:
ORA-02437: cannot validate (TEST.ATT_PK) - primary key violated
SQL> select * from exceptions;
ROW_ID OWNER TABLE_NAME CONSTRAINT
AAAC/yAAGAAAAAOAAB TEST ATTENDANCE ATT_PK
AAAC/yAAGAAAAAOAAA TEST ATTENDANCE ATT_PK
SQL> select * from attendance where rowid in (select row_id from exceptions);
DEPT_ID ATT_DATE ATT_KIND
100 20-FEB-10 1
100 20-FEB-10 1
SQL>Asif Momen
http://momendba.blogspot.com
Similar Messages
-
Hi,
can any one help me the query to find the duplicate data from a column.maybe this example might be of some help.
SQL> select * from employees;
YEAR EM NAME PO
2001 04 Sarah 02
2001 05 Susie 06
2001 02 Scott 91
2001 02 Scott 01
2001 02 Scott 07
2001 03 Tom 81
2001 03 Tom 84
2001 03 Tom 87
8 rows selected.
SQL> -- based on the output above we know that there is duplicates on scott and tom
SQL> -- now we need to identified how many are duplicates by grouping into year, empcode, and name
SQL> select year, empcode, name, position,
2 row_number() over (partition by year, empcode, name
3 order by year, empcode, name, position) as rn,
4 count(*) over (partition by year, empcode, name) as cnt
5 from employees;
YEAR EM NAME PO RN CNT
2001 02 Scott 01 1 3
2001 02 Scott 07 2 3
2001 02 Scott 91 3 3
2001 03 Tom 81 1 3
2001 03 Tom 84 2 3
2001 03 Tom 87 3 3
2001 04 Sarah 02 1 1
2001 05 Susie 06 1 1
8 rows selected.
SQL> -- we have identified the duplicates on the above outputs by the counts
SQL> -- now we want to query only rows that has duplicates
SQL> select emp.year, emp.empcode, emp.name, emp.position, emp.cnt
2 from (select year, empcode, name, position,
3 row_number() over (partition by year, empcode, name
4 order by year, empcode, name, position) as rn,
5 count(*) over (partition by year, empcode, name) as cnt
6 from employees) emp
7 where rn = 1
8 and cnt > 1;
YEAR EM NAME PO CNT
2001 02 Scott 01 3
2001 03 Tom 81 3
SQL> -
Query to find duplicate sql executed
What is the sql to find the duplicate sql executed and count of executions.
I need the query ( though we can get directly the results from OEM)
Please let me know.
Thanks
Naveen>
What is the sql to find the duplicate sql executed and count of executions.
I need the query ( though we can get directly the results from OEM)Get to know V$SQL, V$SQL_AREA and V$SQL_TEXT.
Check out Christoper Lawson's Oracle performance tuning book - it's
very good on the basics of this subject.
HTH.
Paul...
Naveen--
When asking database related questions, please give other posters
some clues, like OS (with version), version of Oracle being used and DDL.
Other trivia such as CPU, RAM + Disk configuration might also be useful.
The exact text and/or number of error messages is useful (!= "it didn't work!"). Thanks.
Furthermore, as a courtesy to those who spend time analysing and attempting to help,
please do not top post and do try to trim your replies! -
Query to find duplicates, update appropriately, delete one of those duplicate
I have duplicate rows in below given table and need to cleanse it by observing another duplicate record.
I'd like to know various ways to achieve it. (I'm confused I should use UPDATE.. (CASE WHEN.. THEN).. or MERGE or something else)
Please find below DDL/DML.
create table MyTable
PKey int identity(1,1),
CustID int,
FirstName varchar(10),
LastName varchar(10),
Main varchar(10),
Department varchar(10)
Insert into MyTable
select 101, 'aaa','bbb','VM','Marketing' union
select 101, '', '','','' union
select 102, '', 'yyy', 'Main', 'Marketing' union
select 102, 'xxx','','','' union
select 103, 'ppp', 'qqq', '', 'HR' union
select 103, '', '', 'MF', '' union
select 104, 'mmm', 'nnn', 'f', 'dept'
select * from mytable
--PKey CustID FirstName LastName Main Department
--2 101 aaa bbb VM Marketing
--3 102 xxx yyy Main Marketing
--6 103 ppp qqq MF HR
--7 104 mmm nnn f dept
Cheers,
Vaibhav ChaudhariHi Vaibhav,
Manu's has copied as a part of the below code.
create table MyTable
PKey int identity(1,1),
CustID int,
FirstName varchar(10),
LastName varchar(10),
Main varchar(10),
Department varchar(10)
Insert into MyTable--(CustID,FirstName,LastName,Main,Department)
select 101, 'aaa','bbb','VM','Marketing' union
select 101, '', '','','' union
select 102, '', 'yyy', 'Main', 'Marketing' union
select 102, 'xxx','','','' union
select 103, 'ppp', 'qqq', '', 'HR' union
select 103, '', '', 'MF', '' union
select 104, 'mmm', 'nnn', 'f', 'dept'
SELECT * FROM MyTable;
;WITH cte AS
SELECT DISTINCT
MAX(PKey) PKey,
CustID,
MAX(FirstName) AS FirstName,
MAX(LastName)AS LastName,
MAX(Main) AS Main,
MAX(Department) AS Department
FROM mytable
GROUP BY CustID
MERGE mytable AS Tar
USING cte AS Src
ON Tar.PKey = Src.PKey
WHEN MATCHED THEN
UPDATE SET Tar.CustID = Src.CustID, Tar.FirstName = Src.FirstName,Tar.LastName = Src.LastName, Tar.Main = Src.Main,Tar.Department = Src.Department
WHEN NOT MATCHED BY SOURCE THEN
DELETE
SELECT * FROM MyTable
DROP TABLE MyTable;
If you do care about the Identity Pkey, as per the expected output, my understanding on your logic is like below.
;WITH cte AS
SELECT PKey, CustID,V1,V2,V3,V4,ROW_NUMBER() OVER(PARTITION BY CustID ORDER BY v1+v2+v3+v4 DESC) AS RN
FROM MyTable
CROSS APPLY(SELECT CASE WHEN FirstName ='' THEN 0 ELSE 1 END AS v1) AS cat1
CROSS APPLY(SELECT CASE WHEN LastName ='' THEN 0 ELSE 1 END AS v2) AS cat2
CROSS APPLY(SELECT CASE WHEN Main ='' THEN 0 ELSE 1 END AS v3) AS cat3
CROSS APPLY(SELECT CASE WHEN Department ='' THEN 0 ELSE 1 END AS v4) AS cat4
,cte2 AS
SELECT DISTINCT
CustID,
MAX(FirstName) AS FirstName,
MAX(LastName)AS LastName,
MAX(Main) AS Main,
MAX(Department) AS Department
FROM mytable
GROUP BY CustID
,cte3 AS
SELECT c2.CustID,c2.FirstName,c2.LastName,c2.Main,c2.Department,c.PKey FROM cte2 c2 JOIN cte c ON c.CustID = c2.CustID WHERE NOT EXISTS(SELECT 1 FROM cte WHERE RN<c.RN)
MERGE mytable AS Tar
USING cte3 AS Src
ON Tar.PKey = Src.PKey
WHEN MATCHED THEN
UPDATE SET Tar.CustID = Src.CustID, Tar.FirstName = Src.FirstName,Tar.LastName = Src.LastName, Tar.Main = Src.Main,Tar.Department = Src.Department
WHEN NOT MATCHED BY SOURCE THEN
DELETE
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
Query to find duplicate referance numbers
Dear,
We have somehow managed to create the same sales order twice or more. In the field "Customer Ref. No." we always type in BP's ref. no. So what I need is a query which will show me all open sales orders which have more than one identical "Customer Ref. No." (ORDR.NumAtCard)
So what I got so far is:
SELECT T0.[DocNum], T0.[NumAtCard] FROM ORDR T0 WHERE T0.[DocStatus] <> 'C' AND ????
Hope anyone can help. Thanks.
BR
Kjetil SandvikHi Kjetil Sandvik,
If you want to block Sales Order with duplicare Customer Ref. No then
Try this SP.....
if (@object_type = '17')
and (@transaction_type= 'A' or @transaction_type= 'U')
begin
declare @Refno as varchar(100), @Cust as varchar(100)
if @object_type = '17'
begin
select @Refno = NumAtCard,
@Cust=CardCode
from ordr
where DocEntry =@list_of_cols_val_tab_del
if 1 != (select count(DocEntry) from ordr with(nolock) where NumAtCard = @Refno and CardCode=@Cust)
begin
select @error = 1
select @error_message = 'Customer Ref. No Should Not Be Repeated. ! '
end
end
end
Thanks,
Srujal Patel -
Query to find duplicate records (Urgent!!!!)
Hi,
I have a to load data from a staging table to base table but I dont want to load data already present in the base table. Criteria to identify the duplicate data is thorugh a field say v_id and status_flag. If these two are the same in both staging and base table then that record must be rejected as a duplicate record.
Kindly help me with the SQL which i need to use in a Procedure.
ThanksHello
Another alternative would be to use MINUS if the table structures match:
--Source rows the first 5 are in the destination table
SQL> select * from dt_test_src;
OBJECT_ID OBJECT_NAME
101081 /1005bd30_LnkdConstant
90723 /10076b23_OraCustomDatumClosur
97393 /103a2e73_DefaultEditorKitEndP
106075 /1048734f_DefaultFolder
93337 /10501902_BasicFileChooserUINe
93013 /106faabc_BasicTreeUIKeyHandle
94929 /10744837_ObjectStreamClass2
100681 /1079c94d_NumberConstantData
90909 /10804ae7_Constants
102543 /108343f6_MultiColorChooserUI
92413 /10845320_TypeMapImpl
89593 /10948dc3_PermissionImpl
102545 /1095ce9b_MultiComboBoxUI
98065 /109cbb8e_SpanShapeRendererSim
103855 /10a45bfe_ProfilePrinterErrors
102145 /10a793fd_LocaleElements_iw
98955 /10b74838_SecurityManagerImpl
103841 /10c906a0_ProfilePrinterErrors
90259 /10dcd7b1_ProducerConsumerProd
100671 /10e48aa3_StringExpressionCons
20 rows selected.
Elapsed: 00:00:00.00
--Destination table contents
SQL> select * from dt_test_dest
2 /
OBJECT_ID OBJECT_NAME
101081 /1005bd30_LnkdConstant
90723 /10076b23_OraCustomDatumClosur
97393 /103a2e73_DefaultEditorKitEndP
106075 /1048734f_DefaultFolder
93337 /10501902_BasicFileChooserUINe
Elapsed: 00:00:00.00
--try inserting everything which will fail because of the duplicates
SQL> insert into dt_test_dest select * from dt_test_src;
insert into dt_test_dest select * from dt_test_src
ERROR at line 1:
ORA-00001: unique constraint (CHIPSDEVDL1.DT_TEST_PK) violated
Elapsed: 00:00:00.00
--now use the minus operator to "subtract" rows from the source set that are already in the destination set
SQL> insert into dt_test_dest select * from dt_test_src MINUS select * from dt_test_dest;
15 rows created.
Elapsed: 00:00:00.00
SQL> select * from dt_test_dest;
OBJECT_ID OBJECT_NAME
101081 /1005bd30_LnkdConstant
90723 /10076b23_OraCustomDatumClosur
97393 /103a2e73_DefaultEditorKitEndP
106075 /1048734f_DefaultFolder
93337 /10501902_BasicFileChooserUINe
89593 /10948dc3_PermissionImpl
90259 /10dcd7b1_ProducerConsumerProd
90909 /10804ae7_Constants
92413 /10845320_TypeMapImpl
93013 /106faabc_BasicTreeUIKeyHandle
94929 /10744837_ObjectStreamClass2
98065 /109cbb8e_SpanShapeRendererSim
98955 /10b74838_SecurityManagerImpl
100671 /10e48aa3_StringExpressionCons
100681 /1079c94d_NumberConstantData
102145 /10a793fd_LocaleElements_iw
102543 /108343f6_MultiColorChooserUI
102545 /1095ce9b_MultiComboBoxUI
103841 /10c906a0_ProfilePrinterErrors
103855 /10a45bfe_ProfilePrinterErrors
20 rows selected.You could use that in conjunction with the merge statement to exclude all trully duplicated rows and then update any rows that match on the id but have different statuses:
MERGE INTO dest_table dst
USING( SELECT
v_id,
col1,
col2 etc
FROM
staging_table
MINUS
SELECT
v_id,
col1,
col2 etc
FROM
destination_table
) stg
ON
(dts.v_id = stg.v_id)
WHEN MATCHED THEN....HTH -
Finding duplicate values in a column with different values in a different c
I'm finding duplicate values in a column of my table:
select ba.CLAIM_NUMBER from bsi_auto_vw ba
group by ba.CLAIM_NUMBER
having count(*) > 1;
How can I modify this query to find duplicate values in that column where I DON'T have duplicate values in a different specific column in that table (the column CLMT_NO in my case can't have duplicates.)?Well, you can use analytics assuming you don't mind full scanning the table.....
select
count(owner) over (partition by object_type),
count(object_type) over (partition by owner)
from all_objects;You just need to intelligently (i didn't here) find your "window" (partition clause) to sort the data over, then make use of that (the analytics would be in a nested SQL and you'd then evaluate it in outside).
Should be applicable if i understand what you're after.
If you post some sample data we can mock up a SQL statement for you (if what i tried to convey wasn't understandable). -
How to find duplicate row in sql query?
Hi All,
Please solve my query, find duplicate row and how to count its. your suggestion would be greatly appreciated.You can use group by and having.
SQL> WITH t
2 AS (SELECT LEVEL id
3 FROM DUAL
4 CONNECT BY LEVEL <= 5
5 UNION ALL
6 SELECT LEVEL + 2
7 FROM DUAL
8 CONNECT BY LEVEL <= 3)
9 SELECT *
10 FROM t;
ID
1
2
3
4
5
3
4
5
8 rows selected.
SQL> WITH t
2 AS (SELECT LEVEL id
3 FROM DUAL
4 CONNECT BY LEVEL <= 5
5 UNION ALL
6 SELECT LEVEL + 2
7 FROM DUAL
8 CONNECT BY LEVEL <= 3)
9 SELECT id, COUNT (*)
10 FROM t
11 GROUP BY id
12 HAVING COUNT (*) > 1;
ID COUNT(*)
3 2
4 2
5 2
SQL> -
Find Duplicate Query MySQL Syntax
There is a "find duplicates" query in SQL that is very useful
but I'm not sure what the syntax is for MySQL. It probably has
something to do with select distinct, group by but I'm not used to
to using these.
This is one that finds all duplicates of [FULLNAME]
SELECT CONTACTS.*
WHERE (((CONTACTS.FULLNAME) In (SELECT [FULLNAME] FROM
[CONTACTS] As Tmp GROUP BY [FULLNAME]
HAVING Count(*)>1 )))
ORDER BY CONTACTS.FULLNAME, CONTACTS.COMPANY
Does anyone know?RichardODreamweaver wrote:
> There is a "find duplicates" query in SQL that is very
useful but I'm not sure
> what the syntax is for MySQL.
SELECT COUNT(*) AS repetitions, FULLNAME, COMPANY
FROM CONTACTS
GROUP BY FULLNAME, COMPANY
HAVING repetitions > 1
It's not something I have used myself, but I got it from
MySQL Cookbook
by Paul DuBois, published by O'Reilly. I have the first
edition, which
covers MySQL 4.0. I think the second edition covers MySQL
5.0.
If you're using MySQL on a regular basis, you or your
employer should
buy it immediately. It will solve most of your problems and
repay its
cost many times over.
David Powers, Adobe Community Expert
Author, "Foundation PHP for Dreamweaver 8" (friends of ED)
Author, "PHP Solutions" (friends of ED)
http://foundationphp.com/ -
Help with Finding Duplicate records Query
HI,
I am trying to write a query that will find duplicate records/cases.
This query will be used in a report.
So, here are the requirements:
I need to find duplicate cases/records based on the following fields:
DOB, DOCKET, SENT_DATEI was able to do that with the following query. The query below is able to give me all duplicate records based on the Criteria above
SELECT DEF.BIRTH_DATE DOB,
S.DOCKET DOCKET,
S.SENT_VIO_DATE SENT_DATE, COUNT(*)
FROM SENTENCES S,
DEFENDANTS DEF
WHERE S.DEF_ID = DEF.DEF_ID
AND S.CASE_TYPE_CODE = 10
GROUP BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE
HAVING COUNT(*) > 1;
//I AM GOING TO CALL THIS QUERY 'X'Now, the information to be displayed on the report: defendants Name, DOB, District, Docket, Def Num, Sent Date, and PACTS Num if possible.
The problem that I need help on is how to combine those queries together (what I mean is a sub query). the 'X' query returns multiple values. please have a look at the comments on the query below to see what I'm trying to achieve.
here is the main query:
SELECT INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
DEF.BIRTH_DATE DOB,
TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
S.DOCKET DOCKET,
S.DEF_NUM DEF_NUM,
S.SENT_VIO_DATE SENT_DATE,
DEF.PACTS_ID PACTS_NUM
FROM USSC_CASES.DEFENDANTS DEF,
USSC_CASES.SENTENCES S,
LOOKUP.DISTRICTS DIST
WHERE DEF.DEF_ID = S.DEF_ID
AND S.DIST_ID = DIST.USSC_DISTRICT_ID
AND S.CASE_TYPE_CODE = 10
AND S.USSC_ID IS NOT NULL
AND // what i'm trying to do is: DOB, DOCKET, SENT_DATE IN ('X' QUERY), is this possible ??
ORDER BY DEFENDANT_NAME; thanks in advance.
I am using Oracle 11g, and sql developer.
if my approach doesn't work, is there a better approach ?
Edited by: Rooney on Jul 11, 2012 3:50 PMIf I got it right, you want to join table USSC_CASES.DEFENDANTS to duplicate rows in USSC_CASES. If so:
SELECT INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
DEF.BIRTH_DATE DOB,
TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
S.DOCKET DOCKET,
S.DEF_NUM DEF_NUM,
S.SENT_VIO_DATE SENT_DATE,
DEF.PACTS_ID PACTS_NUM
FROM USSC_CASES.DEFENDANTS DEF,
SELECT *
FROM (
SELECT S.*,
COUNT(*) OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE) CNT
FROM USSC_CASES.SENTENCES S
WHERE CNT > 1
) S,
LOOKUP.DISTRICTS DIST
WHERE DEF.DEF_ID = S.DEF_ID
AND S.DIST_ID = DIST.USSC_DISTRICT_ID
AND S.CASE_TYPE_CODE = 10
AND S.USSC_ID IS NOT NULL
ORDER BY DEFENDANT_NAME;If you want to exclude duplicates from the query and do not care which row out of duplicate rows to choose:
SELECT INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
DEF.BIRTH_DATE DOB,
TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
S.DOCKET DOCKET,
S.DEF_NUM DEF_NUM,
S.SENT_VIO_DATE SENT_DATE,
DEF.PACTS_ID PACTS_NUM
FROM USSC_CASES.DEFENDANTS DEF,
SELECT *
FROM (
SELECT S.*,
ROW_NUMBER() OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE ORDER BY 1) RN
FROM USSC_CASES.SENTENCES S
WHERE RN = 1
) S,
LOOKUP.DISTRICTS DIST
WHERE DEF.DEF_ID = S.DEF_ID
AND S.DIST_ID = DIST.USSC_DISTRICT_ID
AND S.CASE_TYPE_CODE = 10
AND S.USSC_ID IS NOT NULL
ORDER BY DEFENDANT_NAME;SY. -
Script to find duplicate index and how can we tell if an index is REALLY a duplicate?
Does any one have script to find duplicate index? and how can we tell if an index is REALLY a duplicate?
RahulOne more written by Itzik Ben-Gan
The first query finds exact matches. The indexes must have
the same key columns in the same order, and the same included columns but in any order.
These indexes are sure targets for elimination. The only caution would be to check for index hints.
-- exact duplicates
with indexcols as
select object_id as id, index_id as indid, name,
(select case keyno when 0 then NULL else colid end as [data()]
from sys.sysindexkeys as k
where k.id = i.object_id
and k.indid = i.index_id
order by keyno, colid
for xml path('')) as cols,
(select case keyno when 0 then colid else NULL end as [data()]
from sys.sysindexkeys as k
where k.id = i.object_id
and k.indid = i.index_id
order by colid
for xml path('')) as inc
from sys.indexes as i
select
object_schema_name(c1.id) + '.' + object_name(c1.id) as 'table',
c1.name as 'index',
c2.name as 'exactduplicate'
from indexcols as c1
join indexcols as c2
on c1.id = c2.id
and c1.indid < c2.indid
and c1.cols = c2.cols
and c1.inc = c2.inc;
The second variation of this query finds partial, or duplicate, indexes
that share leading key columns, e.g. Ix1(col1, col2, col3) and Ix2(col1, col2)
would be considered duplicate indexes. This query only examines key columns and does not consider included columns.
These types of indexes are probable dead indexes walking.
-- Overlapping indxes
with indexcols as
select object_id as id, index_id as indid, name,
(select case keyno when 0 then NULL else colid end as [data()]
from sys.sysindexkeys as k
where k.id = i.object_id
and k.indid = i.index_id
order by keyno, colid
for xml path('')) as cols
from sys.indexes as i
select
object_schema_name(c1.id) + '.' + object_name(c1.id) as 'table',
c1.name as 'index',
c2.name as 'partialduplicate'
from indexcols as c1
join indexcols as c2
on c1.id = c2.id
and c1.indid < c2.indid
and (c1.cols like c2.cols + '%'
or c2.cols like c1.cols + '%') ;
Be careful when dropping a partial duplicate index if the two indexes differ greatly in width.
For example, if Ix1 is a very wide index with 12 columns, and Ix2 is a narrow two-column index
that shares the first two columns, you may want to leave Ix2 as a faster, tighter, narrower index.
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Query to find customers who have not purchased anything
I have a query to find customers who have purchased what we call consumables (using item property) over a given period:
SELECT T0.CardCode, T0.CardName, T0.DocDate, T0.DocTotal, T1.ItemCode, T1.Dscription,T1.quantity, T2.ItmsGrpNam
FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry, OITG T2
WHERE T0.DocDate BETWEEN '[%0]' AND '[%1]' AND T1.ItemCode like '2ssy%' AND T2.ItmsGrpNam = 'consumable'
I have another to show customers who have a particular type of equipment:
SELECT T0.manufSN,T0.itemName, T3.Name, T2.Address, T2.Street, T2.Block, T2.City, T2.County, T2.ZipCode
FROM OINS T0 INNER JOIN OCRD T1 ON T0.customer = T1.CardCode INNER JOIN CRD1 T2 ON T1.CardCode = T2.CardCode Inner Join OCPR T3 ON T0.ContactCod = T3.CntctCode
WHERE T0.manufSN like 'P%' AND T2.AdresType= 'S'
What I would like is to find those customers who have this equipment (query 2) but who have NOT purchased and consumables in say the last year.
I have tried using Excel by finding duplicates and taking those in query 1 from those in query 2 but it's very messy.
Has anyone done anything like this or got any good ideas?
ThanksHi Ralph,
Well, I enjoy teaching, so let's start at the beginning. SQL is a fairly full-featured language, and it supports recursion and nesting. That's why the books online often describe elements of the SQL statements as "expression" - it may be more than a field or a simple function occurring there. Nesting is the little puppy we used here.
Now, in your first post, you said: "What I would like is to find those customers who have this equipment (query 2) but who have NOT purchased and consumables (query 1) in say the last year."
So, our common point between the two queries is the customer, the CardCode. That's what this part does: F0.CardCode = T0.Customer. In my internal convention, I used F for Filter. So we only want the results in the filter where the CardCode matches the CardCode/Customer from the main query tables. It's the sole contact point between the two queries.
You also said you wanted only the items where they had purchased no consumables, which basically translates into: a count of the records equals 0. Now, since all we're interested in from the second query, the consumables query is how many records we returned, we get rid of all the columns except for one that we apply a COUNT to. After that, it's a simple criteria: the result of the second query has to equal 0. This is how the criteria looks after you take out all the details and put only the important brackets in: (SELECT COUNT...FROM...WHERE...) = 0.
This might be confusing at first, because most of the time we return recordsets from queries, but a standard feature of SQL is to return a value of any data type if the query returns a single row and a single column. This wouldn't work at all if we had more than one column in our nested query (or would require lots of tweaking), and although it returns a number of results in the complete process of the whole SQL statement, it only returns one result for each row.
Regards,
Mark Dielmann
Edited by: Mark Dielmann on Nov 13, 2009 12:30 PM - Forum doesn't support advanced formatting on answered questions.
Edited by: Mark Dielmann on Nov 13, 2009 12:32 PM - Salutations and more formatting.
Edited by: Gordon Du on Nov 13, 2009 10:35 AM - There are maximum characters limitation for correct format -
Help needed in finding duplicate entries in invoices
Hi,
let me explian u the senario.
when we enter the invoice no. in vf03 and select any item and click on pricing button.
there i find the Cnty fild having duplicate entries like xr1 2 times and xr2,xr3,xr4,xr5 and xr6 all 2 times
so i need to write a query to find out which of all the invoices have these types of duplicate entries.
regards,
maqsoodHi!
CnTy is header line of condition type column.
There can be several reasons, why conditions types are twice in a document. E.g. conditions can be given on header and line level, so they are two times in a document.
These tax conditions are just line level. But please check, if they have different colors. I currently don't remember if only the blue or only the black lines (with or without highlight) are relevant for the document.
The inactive conditions are still shown, but not 'counted'. You can set conditions inactive by requirements, by formula, by exclusion groups... so there are many ways to set the system up.
Only if your total is wrong you have to do something (e.g. give users a training how to create a sales order / invoice).
Conditions for invoice can be found in KONV with KONV-KNUMV = VBRK-KNUMV.
Regards,
Christian -
Find duplicates from different tables
I need to write a sql query to find out in which table
holds the duplicate data.
Duplicate : AAA company should be present(mapped) only once with XXX Partner. If it is repeated then would be considered
as duplicate
Please help in writing this query
Table A
Table B
Table C
company Partners company Partners
company Partners
AAA XXX AAA
XXX
AAA XXX
BBB YYY BBB
YYY
BBB YYY
AAA XXXX (duplicate Data)
Expected o/p :
table A contains duplicate data , or Table B contains Duplicate Data ETc...Chelseasadhu, I do not think AAA is duplicating as the partners are different XXX and XXXX.
Could you please clarify how are you finding its a duplicate value? Just the Company duplicate is your criteria?
You may try something below:
create Table TableA(Company varchar(100), Partners varchar(100))
Insert into TableA Select 'AAA','XXX'
Insert into TableA Select 'BBB','XXX'
Insert into TableA Select 'AAA','XXXX'
create Table TableB(Company varchar(100), Partners varchar(100))
Insert into TableB Select 'AAA','XXX'
Insert into TableB Select 'BBB','XXX'
--Insert into TableB Select 'BBB','XXXCC'
create Table TableC(Company varchar(100), Partners varchar(100))
Insert into TableC Select 'AAA','XXX'
Insert into TableC Select 'BBB','XXX'
Declare @DuplicateTableA int =0,@DuplicateTableB int=0,@DuplicateTableC int=0
Set @DuplicateTableA=(Select Case when exists(Select COUNT(1) From TableA Group by Company having COUNT(1)>1) then 1 else 0 end)
Set @DuplicateTableB=(Select Case when exists(Select COUNT(1) From TableB Group by Company having COUNT(1)>1) then 1 else 0 end)
Set @DuplicateTableC=(Select Case when exists(Select COUNT(1) From TableC Group by Company having COUNT(1)>1) then 1 else 0 end)
/* Once you have the existence info, its easy for you to do the display at your application layer*/
Declare @DisplayText Varchar(MAX) =''
Set @DisplayText = (Select Case when @DuplicateTableA = 1 then 'TableA contains duplicate data' else '' end)
Set @DisplayText = @DisplayText+(Select Case when Len(@DisplayText)=0 then '' else ' ' End + Case when @DuplicateTableB = 1 then 'TableB contains duplicate data' else '' end)
Set @DisplayText = @DisplayText+(Select Case when Len(@DisplayText)=0 then '' else ' ' End + Case when @DuplicateTableC = 1 then 'TableC contains duplicate data' else '' end)
Select @DisplayText
Drop table TableA,TableB,TableC -
How to create an activity when system finds duplicate record!!
Hi CRM Experts,
I am working on CRM 5.0. We are uploading contact details to CRM through ELM.
Here My queries are:
1) How to create An Activity when system finds duplicate record?
2) By using ELM we can create BP with Activities and BP with Leads. But Here, my scenario is we have to Create BP with leads and Acivities. can any one help me on these areas?
Thank in Advance.
SreeHi Sree,
I can help you with your first query.
When the system finds a duplicate record then either the system stops working further or proceeds with the error free record.
So once the duplicate entry is found only the first record will be considered and not the second or the duplicate record.
Regards,
Rekha Dadwal
Kindly reward with points if usefull !!!!
Maybe you are looking for
-
Ageing Report for Outstanding Amount from Customer
Dear All, Kindly let me know if any ageing report available to find the out the outstanding amount for list of customers? We want to know how many days customers crossed their credit period? If the customer has 50 days credit, it may be crossed 50 da
-
Import photo in jpeg-format from email
when I try to import photos in jpeg format from an email a window appears :" unreadable data " and the photos are not imported in the library of iPhoto, my iPhoto version :5.0.4 (263)
-
The fields which represent prices are not sorted logically at all, whether I set the column type to "number" or not. If the price list contains values {90, 60.5, 42.5, 400}, sorted ascending gives {90, 60.5, 42.5, 400} and descending {400, 42.5, 60.5
-
ZTABLE TRANSPORT WITH CONTENTS TO PRODUCTION SERVER
Hi Friends, I had created a ztable in Developement server with 3 fields including MANDT field and added 15 records to that table. (MANDT = 500). When I transport to QA Server, the data entered in the development server, are not visible. Again I ent
-
Where to configure the reason code for payment differene
Dear Experts, I did the settings in obxl with reason code option and changed the screen layout for the postings keys for payment difference as mandatory. while doing the account assignment in obxl system asking the reason code for payment difference.