Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server & have generously sponsored dedicated servers and web hosting to ensure a reliable and scalable dedicated hosting solution for

Join Returns Duplicate Rows

I'm having a little trouble with the following code:

SELECT DISTINCT cd1.*, cd2.*
FROM Table1 cd1 LEFT JOIN Table2 cd2
ON cd1.RegNr=cd2.RegNr
WHERE cd1.RegNr = $RegNr

I want it to return the 2 rows that is present in the tables but it returns 4.

1262007-10-20 10:14:00
1262007-10-20 10:14:00
1262007-10-20 10:17:00
1262007-10-20 10:17:00

View Complete Forum Thread with Replies
Sponsored Links:

Related Messages:
Unique Index Returns Duplicate Rows
We are running the following query, which has a unique index on Table_2 (col1 and sys1), and Column col1 from Table_1 is unique.

select top 100 s.*, x.col1
from Table_1 s
left outer join Table_2 x
on x.col1 = s.col1 and x.sys1 = 'SYSTEM0'

Unfortunately this query returns duplicate rows. And every time the result is different

But once we dbcc dbreindex the unique index on Table_2, the result will not have any dups.

Any ideas?



View Replies !   View Related
Join Only Returns The Read Rows :|
Hi all,

I am trying to build a association table (t2) to store a list of users
have viewed an item in my records table (t1). My goal is to send the
UserID parameter to the query and return to the user a read / not read
marker from the query so I can handle the read ones differently in my
.net code. The problem is that I cannot work out how to return anything
but the read data to the client. So far my stored proc looks like this

SET @UserID = 219 -- FOR TESTING

SELECT t1.strTitle, t1.MemoID, Count(t2.UserID) AS ReadCount,t2.UserID

t2 ON t1.MemoID = t2.MemoID

WHERE t2.UserID = @UserID

GROUP BY t1.MemoID, t1.strTitle,t2.UserID

It works fine but only returns those records from t1 that are read. I
need to return the records with null values also! I may have built the
assoc table wrong and would really appreciate some pointers on what I
am doing wrong. (assoc table has rID, MemoID and UserID columns)

Please help!

Many thanks

View Replies !   View Related
INNER JOIN Between A CLR-TVF And A Table Returns No Rows
I have the following query:

select sq.*, p.numero, p.nombre
from paf p right outer join dbo.GetListOfSquaresForShippingLot(@lot) sq on sq.number = p.numero and sq.version = p.numero

The @lot parameter is declared at the top ( declare @lot int; set @lot = 1; ). GetListOfSquaresForShippingLot is a CLR TVF coded in C#. The TVF queries a XML field in the database and returns nodes as rows, and this is completed with information from a table.

If I run a query with the TVF only, it returns data; but if I try to join the TVF with a table, it returns empty, even when I'm expecting matches. I thought the problem was the data from the TVF was been streamed and that's why it could not be joined with the data from the table.

I tried to solve that problem by creating a T-SQL multiline TVF that is supposed to generate a temporary table. This didn't fix the problem.

What can I do? Does anybody know if I can force the TVF to render its data somewhere so the JOIN works? I was thinking a rowset function could help, but I just can't figure out how.


Let me know if you want the code for the CLR TVF. This is the code for the T-SQL TVF:

CREATE FUNCTION [dbo].[GetTabListOfSquaresForShippingLot]
@ShippingLot int
@result TABLE
Number int, Version int, Position smallint,
SubModel smallint, Quantity smallint,
SquareId nvarchar(5),
ParentSquareId nvarchar(5),
IsSash smallint,
IsGlazingBead smallint,
Width float,
Height float,
GlassNumber smallint,
GlassWidth float,
GlassHeight float
FROM dbo.GetListOfSquaresForShippingLot(@ShippingLot)


View Replies !   View Related
Table Join Statement Returns Repeat Rows
Hello All.

I am struggling with the below join block in my stored procedure.
I can't seem to get the duplicate row problem to go away. It seems that SQL is treating each new instance of an email address as reason to create a new row despite the UNIONs.
I understand that if I am using UNION, using DISTINCT is redundant and will not solve the duplicate row problem.

Primary Keys: none of the email address columns are primary keys. Each table has an incrementing ID column that serves
as the primary key.

I am guessing I am encountering this problem because of how
I have structured my Join statements? Is it possible to offer advice without a deeper understanding of my data model or
do you need more information?

Thanks for any tips.


select emailAddress from Users union
select user_name from PersonalPhotos union
select email_address from EditProfile union
select email_address from SavedSearches union
select distinct email_address from UserPrecedence union
select email_address from LastLogin) drv
Left Join Users tab1 on (drv.emailAddress = tab1.emailAddress)
Inner Join UserPrecedence tab5 on tab5.UserID=tab1.UserID
Left Join PersonalPhotos tab2 on (drv.emailAddress = tab2.user_name)
Left Join LastLogin tab4 on (drv.emailAddress = tab4.email_address)
Left Join EditProfile tab3 on (drv.emailAddress = tab3.email_address)
Left Join SavedSearches tab6 on (drv.emailAddress = tab6.email_address

View Replies !   View Related
How To Remove Duplicate Rows From Full Join Query
I have 4 tables (SqlServer2000/2005). In the select query, I have FULL JOINED all the four tables A,B,C,D as I want all the data. The result is as sorted by DDATE desc:- 
AID     BID      BNAME          DDATE                                   DAUTHOR
1          1          abcxyz              2008-01-20 23:42:21.610
1          1          abcxyz              2008-01-20 23:41:52.970
1          2          xyzabc              2008-01-21 00:17:14.360
1          2          xyzabc              2008-01-20 23:43:17.110        
1          2          xyzabc              2008-01-20 23:42:43.937
1          2          xyzabc              NULL                                      NULL
2          3          pqrlmn              NULL                                      NULL
2          4          cdefgh              NULL                                      NULL 
Now, I want unique rows from the above result set like :- 
AID     BID      BNAME          DDATE                                   DAUTHOR
1          1          abcxyz              2008-01-20 23:42:21.610
1          2          xyzabc              2008-01-21 00:17:14.360
2          3          pqrlmn              NULL                                      NULL
2          4          cdefgh              NULL                                      NULL 
I want to remove the duplicate rows and show only the unique rows but contains all the data from the first table A. I have to bind this result set to a nested GridView.

View Replies !   View Related
Case Stmt Returns Duplicate Result
Hi there,

The following is my table whereby i have joined projects table with issue table (this is 1 to many relationship).

I have the following query:
odf.mbb_sector sectorid,

SUM(case when odf.mbb_projecttype = 'lkp_val_appl' then 1 else 0 end) total_appl,
SUM(case when odf.mbb_projecttype = 'lkp_val_infrastructure' then 1 else 0 end) total_infra,
SUM(case when odf.mbb_projecttype = 'lkp_val_eval' then 1 else 0 end) total_eval,
SUM(case when odf.mbb_projecttype = 'lkp_val_subproject' then 1 else 0 end) total_subprj,
SUM(case when odf.mbb_projecttype = 'lkp_val_nonit' then 1 else 0 end) total_nonit,
SUM(case when odf.mbb_projecttype = 'lkp_val_adhocrptdataextract' or
odf.mbb_projecttype = 'lkp_val_productionproblem' or
odf.mbb_projecttype = 'lkp_val_maintwoprogchange' then 1 else 0 end) total_others,
COUNT(distinct prj.prid) total_prj



prj.prid =
AND srm.is_active =1
AND odf.mbb_projecttype not in ('lkp_val_budget','lkp_val_itpc')
AND odf.mbb_funcunit = 'lkp_val_operation'

which returns me the following result :

The problem is at the lkp_val_infosystem where it returns 3 instead of 1 in the total_infra column. How do I correct my case stmt to return the correct no of projects breakdown by different project type? Currently, only the total_prj which returns correct data.


View Replies !   View Related
Select Distinct Rows From Duplicate Rows....
Dear Gurus,I have table with following entriesTable name = CustomerName Weight------------ -----------Sanjeev 85Sanjeev 75Rajeev 80Rajeev 45Sandy 35Sandy 30Harry 15Harry 45I need a output as followName Weight------------ -----------Sanjeev 85Rajeev 80Sandy 30Harry 45ORName Weight------------ -----------Sanjeev 75Rajeev 45Sandy 35Harry 15i.e. only distinct Name should display with only one value of Weight.I tried with 'group by' on Name column but it shows me all rows.Could anyone help me for above.Thanking in Advance.RegardsSanjeevJoin Bytes!

View Replies !   View Related
SQL Call INNER JOIN Returns Too Many Records
I have my SQL call:
SELECT     CallLog.CallID, Journal.HEATSeqFROM         CallLog INNER JOIN                      Journal ON CallLog.CallID = Journal.CallID
There are multiple enteries in the Journal table for every entry in the CallLog table, so I receive multiple records:
CallID           HEATSeq00000164     983290904 00000164     983291548 00000164     983295209 00000231     984818271 00000231     985194317 00000231     985280248
I only want to return the LAST record in the Journal table, so the output will be:
CallID           HEATSeq00000164     983295209 00000231     985280248
Can this be done directly in the SQL call?

View Replies !   View Related
Sys.dm_os_performance_counters Returns Zero Rows
After changing the Service account for a SQL Server 2005 SP2 machine the DMV sys.dm_os_performance_counters
is returning zero rows. These values were availiable prior to change

The change in Service account was done via the Configuration manager and the Service account is also part of the Local Administrator group

Since this change the Performance Counters in Perfmon for SQLSEVERatabases and others are also not availiable

Any suggestions on where to start looking ?


View Replies !   View Related
Group By - Count Returns No Rows
Hi everyone:
I guess this should be a simple question but have not been able to find the answer, does anyone know how to make a SQL Sentence to return at least one row when counting?
SELECT COUNT(Id_Field), Field2  FROM Table1 WHERE Code_Field = 1 GROUP BY Field2
This will return 0 rows when the where criteria is not matched by any record on the Table1, but I would like to have one row counting 0 rows, in stead it returns no rows at all.
Thanks for any help.

View Replies !   View Related
DataAdapter Always Returns 0 Or Empty Rows
Good day,
I just like to ask if anybody has experienced getting empty rows from SQL data adapter? I'm using SQL Server 2005. Problem is when the sql is run on Query Analyzer it retrieves a number of rows but when used in my application it returns 0 or empty rows.
I thought the connection is not the problem since I got my columns right. Below is my code snippet.
const string COMMAND_TEXT = @"select distinct somefield as matchcode, count(somefield) "
+ "as recordcount from filteredaccount where StateCode = 0 group by somefield having count(somefield) > 1";
SqlDataAdapter adapter = new SqlDataAdapter(COMMAND_TEXT, connection);
DataTable dt = new DataTable(sometablename);


View Replies !   View Related
Select * From Sysperfinfo Returns 0 Rows.

I have DB monitoring jobs which use Sysperfinfo to monitor some of the counters. On One SQL 2K Server since few days the select on sysperfinfo returns 0.

Do you think I need to start any service from the OS side to enable this?

Your input is highly apppreciated.


View Replies !   View Related
Join Returns More Than One Row, Post Code Regular Expressions
Hi,I trying to write a select statement that will return each of my salesmen a region code based on a table of post codes using wildcards... eg.MK1 1AA would be matched in the region code table to MK1%SELECT dn.DEALER_CODE, dn.NAME AS DNAME, rc.REGION_ID,rc.POST_CODE, dn.POSTAL_CODEFROM REGIONAL_CODES rc CROSS JOINDEALER_NAW dnWHERE (dn.POSTAL_CODE LIKE rc.POST_CODE)The above statement works BUT there are some post code areas such asour friends in Milton Keynes that are split into two regions... eg MK1is region id 2 and MK10 is region 3.So a dealer with post code MK10 1AA would be matched to both rowsreturning duplicatesPOST_CODE REGION_IDMK1% 2MK10% 3I think the answer would lie in a subquery which returns the ID of theregion with the longest length of the postcode match (e.g.len(POST_CODE) for the rc table... return only the MAX....any ideas????Any help muchos appreciated, and I apologies now for the naming of thedealers name as a reserve word... not me!Ct

View Replies !   View Related
Left Join Returns Values Where I Was Was Expecting Nulls
I have a query which is returning a different result set when it is run against identical tables in 2 different environments.

The query is like:

F.LicenseeID, IsSpecialLicensee
from FactTable F
left join View_SpecialLicensee SL on F.LicenseeID = SL.LicenseeID

The Create Statement for the view is like

Create View [dbo].[View_SpecialLicensee]
Select LicenseeID, LicenseeName, IsSpecialLicensee = 1
from DimensionLicensee
where LicenseeName like '%ibm%'
or LicenseeName like '%cisco%'
or LicenseeName like '%hp%'

In my test environment, I get the query result I expected:
LicenseeID, IsSpecialLicensee
1 , 1 - (where LicenseeName = 'IBM')
2, null - (where LicenseeName = 'Juniper')
3, 1 - (where LicenseeName = 'Cisco')
4, null - (where LicenseeName = 'Microsoft')
5, null - (where LicenseeName = 'Oracle')
6, null - (where LicenseeName = 'Apple')

In my production environment, I get the following query result:
1 , 1 - (where LicenseeName = 'IBM')
2, 1 - (where LicenseeName = 'Juniper')
3, 1 - (where LicenseeName = 'Cisco')
4, 1 - (where LicenseeName = 'Microsoft')
5, 1 - (where LicenseeName = 'Oracle')
6, 1 - (where LicenseeName = 'Apple')

Ideas as to what changed gratefully received.

FYI the production environment which returned the 2nd dataset is SQL2000, I have got the result I expected in both SQL2000 and SQL2005 development environments.

View Replies !   View Related
Select Distinct Returns Multiple Rows With Same Value
I have a Select Distinct myfield that returns multiple rows with same value for myfield when it should only one. Why is this happening?

View Replies !   View Related
Creating SQL Statement That Returns Rows ONLY Between A Certain Date?
I maintain a simple employment (job) tracking web application.

Jobs can be set to 5 different statuses: Open, Closed, Filled, Pending, or Cancelled.

There is a table in the database called statusLog, which records everytime a job is set to opened, or set to closed, etc. It records the job number, the date it was changed, and what the job was changed to.

Here is a short example of what a few entries might look like:

Status Date Job number

Open10/6/2002 2:34:56 PMTEST2845
Hold10/11/2002 12:19:29 PMTEST2845
Closed10/29/2002 2:00:54 PMTEST2845
Pending10/25/2002 3:37:06 PMTEST2877

What I need to do is write an SQL query that will return to me all entries in this table, between two certain dates, that ONLY have entries during those dates.

Basically I need to know how many "new" jobs were set to open during a month. I can easily just do a count of how many jobs were set to open, but this will not give a count of "new" jobs.

Example: during june a job could be set to open. Then in july it could be set to pending. Then in august, it could be re-opened, and set to open.

If I ran this query for the month of August, it would return that job as being opened in august. But it wasn't a new job, meaning it had already been in the system in previous months.

Is there some way I can select all "Open" jobs, between a certain date, that do not exist anywhere in the table previous to the date it was entered? This would give me a result set containing only new jobs.

The only way I've thought of yet is to get a result set of all jobs simply set to open during a month, then one by one for each record, go back and run another SQL query to see if it exists in the table anywhere other than in that month.

This seems horribly inefficient to me however, as I do not want to be doing 34,000 independent SQL calls for every single "open" job it finds during a certain month.


View Replies !   View Related
Xp_AvailableMedia Returns 0 Rows In SQL Server 2005
Without systemAdmin role, xp_AvailableMedia can still run (after granting execute permission) but just return 0 rows.

It seems we have to give the user SystemAdmin role, in order to get the list of devices in SQL 2005, while in previous versions of SQL Server, the user granted the execute permission for xp_AvailableMedia will be able to get the list of devices.

Is this be design? Is there any way the a NON-SA user can retrieve device list? If yes, what extra permissions do we have grant?

Thanks in advance for your help.


View Replies !   View Related
How To Speed Up Stored Procedure That Returns 35,000 Plus Rows Of Data?
I'm pretty new to .NET and am looking for advice on how to speed up a simple stored procedure that returns 35,000 plus rows.   It's a super simple query that returns a client list.  It's just that there is soooooo many rows, it's super slow when the page loads. 

View Replies !   View Related
Problem With DatatTable.GetErrors() Returns All Rows As Having An Error
I have a function in which I generate a group of random numbers, put them in a DataTable & then pass it to the function below which inserts the numbers in the database, the table has the following columns(Key,SectionId, DateCreated) the column Key is the primary keyNow the function that generates the random numbers, might generate a number which was already inserted in a previous insert and since the Key column is the primary key there will be a constraint exception when the dataadapter tries to insert a row that has a duplicate key value, that's why I set the ContinueUpdateOnError property to true coz I want non duplicates rows to be inserted normally & ignore the duplicates, so in the case the sent table had 100 rows, 90 inserted successfully & the rest failed coz they are duplicates, I was planning to get the failed rows by calling GetErrors, but when I did so GetErrors returned all rows as having errors the ones successfully inserted & the ones failed.If I removed the line adapter.UpdateBatchSize = 50; GetErrors will return only failed errors, but I want to do batch updates. How can I make the GetErrors returns failed rows when UpdateBatchSize is set to a value?public static int InsertKeys(DataTable dtKeys)        {            using (SqlConnection connection = new SqlConnection(Common.ConnectionString))            {                using (SqlCommand command = new SqlCommand("Keys_Insert", connection))                {                    command.CommandType = CommandType.StoredProcedure;                    command.Parameters.Add("@Key", SqlDbType.VarChar, 20, "Key");                    command.Parameters.Add("@SectionId", SqlDbType.TinyInt, 1, "SectionId");                    SqlDataAdapter adapter = new SqlDataAdapter();                    adapter.InsertCommand = command;                    adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;                    adapter.ContinueUpdateOnError = true;                    adapter.UpdateBatchSize = 50;                    int recordsAffected = adapter.Update(dtKeys);                    return recordsAffected;                }            }        }

View Replies !   View Related
Inner Join Duplicate Data
i have 2 tables not connected in any way
but both have orderid filed (same filed).
In one table this filed (and onther one) are keys,
the second table dose not hace a key at all.
The same order_id CAN repeat itself in each table.
When i try to join the tables (some rows just in one table and some in both):
Select, tab1.orderid, tab2.sku
from tab1 inner join tab2 on tab1.orderid=tab2.orderid
The result i get is duplicate.
each row is multiple.
What I'm doing wrong?

View Replies !   View Related
Make Tablix Column Group Show When Filter Returns No Rows
I'm runningSQL Server 2008 Feb08 CTP and I've got a tablix with column groupings and row groupings which works nicely, I'm a becomming a big fan of the tablix.

However sometimes the filter I have on a column group returns no records and the whole column group disappears.
Is there any way to make this columnappear with but withempty cells as I have another tablix down the page with the samecolumns and I want the columns to all line up on the multiple tablix.

In Version 2005 I used to achieve the equivalent of a column group within a table by adding a list with filter to the cell, this meant the column always was shown,the tablix allows does this much more elegantly but I'll have to go back to the old methodif I can't make the column remain.

Am I just missing a simple option?


View Replies !   View Related
I used the following select statement to get duplicate records on Case_number column

select cases.distinct case_link, cases.case_number
from cases
group by case_link
having case_number > 1

I got the error message that

"'cases.warrant_number' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
cases.case_number' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

Any idea on a better statement to use. THANKS FOR YOUR HELP!

View Replies !   View Related
Duplicate Rows
I have a table and this is what i did to get the desired result

Select A.col1,count(A.col1)
from Tab1
group by col1
having count(A.Col1) > 1

i tried this - but it didnot worked - it returned col1 as blanks -
Select A.col1,B.Col2,count(A.col1)
from Tab1 A, Tab2 B
where A.col1 = B.col1
group by A.col1 , b.col2
having count(A.Col1) > 1

As I was looking for all the rows that are apperaing more than once.

Now - The problem -

I have to join this table to another table Tab2 to get the other details.
My Tab2 is a table from where I have to pull the Customer DEtails like name,address etc.
How should I write this query?
Any thinuhts?

View Replies !   View Related
Duplicate Rows
Hi. I'm a SQL Server newbie, very experienced with Access, developing an ASP.NET database editor web app. I query the database with a statement more or less in the following form:

SELECT organisation.OrgID, organisation.Name, organisation.whatever FROM services INNER JOIN servicegrouping ON services.serviceID=servicegrouping.serviceID INNER JOIN organisations ON servicegrouping.OrgID = organisations.OrgID WHERE services.service=x OR services.service=y

In other words, I have a database of organisations. The services offered by the organisations are in a separate table, and I only want to return organisations that offer services X or Y.

Okay, now if I did this in Access, this query would return just one record for each organisation that meets the condition, unless I was to include a field from the services table in the SELECT clause, in which case of course I would get one record for each organisation and unique service offered.

But in MS SQL, the query returns duplicate rows if there is more than service offered by the organisation that meets the WHERE condition (=x or =y). Why is this and what do I need to do to my SQL statement to ensure I only get unique rows?

View Replies !   View Related
Duplicate Rows?

i wanna know, how can i check if i have duplicate rows in my table?


View Replies !   View Related
Duplicate Rows

I've a query which gets a set of data from multiple tables -

select *
inner JOINq
inner JOIN t
ON( =
inner JOIN s
ON ( = )
inner join l
on ( =
and =

WHERE = 764
and = '764'

I get repeated # of rows for each id. I've some 136 rows for each ( there are 6 q.ids and hence I get 816 rows instead of 136) These 136 rows are actually divided among thse q.ids as

id=5, 4 rows
id=6, 8 rows
id=7, 24 rows
id=8, 40 rows
id=10, 60 rows
total=136 rows

Let me know what I'm missing here

Thanks for your help!

View Replies !   View Related
How To Avoid Duplicate Cells When Trying To Join 3 Tables?
Hi all,
 Below are my tables:








Jack Table
















3 Table1








JAPAN Table2
I tried to get the Country for all the people in the first table.
My SQL statement is: SELECT Table.Name, Table2.Country FROM Table Left Join Table1 ON Table.Rowid = Table1.Rowid Left Join Table2 ON Table1.Rowid1 = Table2.Rowid1
My final result is shown on Table2. But is it possible if I can generate the results without the duplicate Names (as shown below)?
















Any advice will much appreciated.

View Replies !   View Related
Deleting Duplicate Rows
I have a csv file that I need to import daily into a SQL Server 2005 table. Much of the table contents could just be overwritten with the new csv file, however there are a set of Rows within the table that need to be appended to , rather than overwritten. 
There is no Primary Key in the csv file that can be used.  
I'm not sure this is the best approach, but what I have been trying to do, is append the entire csv file to the existing table, and then go back and delete the duplicates.
When I run the Delete, it does delete the majority of the records, but leaves a couple hundred behind. The number left behind varies with each run, can't seem to identify a pattern here. Running the Delete a second time does clean up the rows left behind in the first execution of the Delete, and gives the result I want.
Any thoughts as to why this needs to be run twice? Or is a better approach available?
Here is my code -
SELECT [Pkg ID], [Elm (s)], [Type Name (s)], [End Exec Date], [End Exec Time], dupcount=count(*)
INTO temppkgactions
FROM pkgactions
GROUP BY [Pkg ID], [Elm (s)], [Type Name (s)], [End Exec Date], [End Exec Time]HAVING count(*) > 1
DELETE TOP (SELECT COUNT(*) -1 FROM dbo.temppkgactions WHERE dupcount > 1 )
FROM dbo.pkgactions
DROP TABLE temppkgactions

View Replies !   View Related
SQL Combining Duplicate Rows, Please HELP.
I have a question, what does a statement look like that finds the duplicate rows and combines them,
I have a table named PRODUCTS in it 3 columbs Cost, Stock, Part_number.
I need to find all Part_numbers that dublicate, Combine the rows into 1 & combine (sum, add) their stock together is the new row & take an avarerage of their cost and use it as cost in the new row where they combine.
Please help me, I am stalled. Looked all over the internet & could not find anything, I really need this for a project I can not finish.
I have the following SQL statement:
SELECT part_number,
COUNT(part_number) AS NumOccurrences
FROM Products
GROUP BY Part_number
HAVING COUNT(part_number) > 1

View Replies !   View Related
Hi everyone.How can I get the unique row from a table which contains multiple rowsthat have exactly the same values.example:create table test (c1 as smallint,c2 as smallint,c3 as smallint )insert into test values (1,2,3)insert into test values (1,2,3)i want to remove whichever of the rows but I want to retain a singlerow.TIADiego

View Replies !   View Related
Merging Duplicate Rows
Hello All,I have an issue with dupliate Contact data. Here it is:I have a Contacts table;CREATE TABLE CONTACTS(SSN int,fname varchar(40),lname varchar(40),address varchar(40),city varchar(40),state varchar(2),zip int)Here is some sample data:SSN: 1112223333FNAME: FRANKLNAME: WHALEYADDRESS: NULLCITY: NULLSTATE NYZIP 10033SSN: 1112223333FNAME: NULLLNAME: WHALEYADDRESS: 100 MADISON AVECITY: NEW YORKSTATE NYZIP NULLHow do I merge the 2 rows to create one row as follows:via SQL or T-SQLSSN: 1112223333FNAME: FRANKLNAME: WHALEYADDRESS: 100 MADISON AVECITY: NEW YORKSTATE NYZIP 10033Pointers appreciated.Thanks

View Replies !   View Related
Top N Rows, Discard Duplicate
I have data in table as follows,NumCategoryProductName---- -------- -----------100AProduct1100BProduct1101AProduct2101BProduct2101AProduct2101BProduct2102AProduct3102BProduct3102CProduct3102DProduct3Can sb pl help to what t-sql query to use to achieve as follows,for some reason, there are duplicate rows, but i need to gettop most rows of category A, B as follows.NumCategoryProductName---- -------- -----------100AProduct1100BProduct1101AProduct2101BProduct2102AProduct3102BProduct3TIAMeDhanush

View Replies !   View Related
Duplicate Rows But No Key On The Tables
Dear All,I have a table with 10 billion records but there are no key on it. I cannotbuild a key on it as it is the data source.However, the data source exits the duplicated rows.I have used the DTS to transform the data into a new table and delete theduplicated rows. As there are 10 billion records, i need to divide it into 3parts and also the process lasts for 6 hours each part.I want to ask is there any other good methods to slove my problem??ThxEsther

View Replies !   View Related
Remove Duplicate Rows
I've got the following table data:116525.99116520.14129965.03129960.12129967.00And I need to write a query to return only rows 2 and 4, since theremaining rows have duplicate IDs. I've tried the Group By, but amhaving no luck.Thanks!

View Replies !   View Related
Suppressing Duplicate Rows
Hi,I need to get a list of columns and corresponding datatypes for thegiven table name. I am using the,b.type_namefromsyscolumns a,master.dbo.spt_datatype_info b,systypes c,sysobjects dwherea.xusertype = c.xusertype andb.ss_dtype = c.xtype anda.ID = (SELECT OBJECT_ID(<tablename>)) anda.ID = d.ID andd.ID = (SELECT OBJECT_ID(<tablename>))This returns multiple sets of data for each column. This is becausethe same column name is repeated in multiple tables in primarykey-foreign key relationships. Is there a way in which I can get onlyone row for each column of a table?

View Replies !   View Related
Delete Duplicate Rows
Suppose that we have the following rows in a MSSQL table :


How to remove duplicates (leave only the 2 first rows) ?

View Replies !   View Related
Delete Duplicate Rows
I have the following query to select duplicate rows from the table. How can i delete them with out using temp table.

select UserName, Title, Name, ColWidth, Sequence
from table1 (nolock))
Group by UserName, Title, Name, ColWidth, Sequence
Having count(*) >1

Any help would be greately appreciated.

View Replies !   View Related
Removing Duplicate Rows

Please give the DML to SELECT the rows avoiding the duplicate rows. Since there is a text column in the table, I couldn't use aggregate function, group by (OR) DISTINCT for processing.

Table :

create table test(col1 int, col2 text)
insert into test values(1, 'abc')
insert into test values(2, 'abc')
insert into test values(2, 'abc')
insert into test values(4, 'dbc')

Please advise,


View Replies !   View Related
Fetching Duplicate Rows

I have some duplicate rows in a table. I didnt define any primary key or unique key on the table.

I can get unique rows using DISTINCT, but i want to fetch only the duplicated rows and also i want to delete the duplicated rows.

How can i do it?

Please help me.....

Thanx in Advance

View Replies !   View Related
Select Duplicate Rows
I get a tabseparated textfile with data every friday. Faulty rows are to be returned to the source.

Double rows are considered a fault. How do I select all double rows?

I join the data later on with four columns so if these columns are alike the rows are considered identical even if other columns are not. Ie:

A, B, C, D, 12, 34, 48, 76
A, B, C, D, 23, 45, 56, 99

These two rows are considered alike since I join on A+B+C+D.

I'd like to select ALL double rows and insert them into a separate table that I can return to the source. Does anyone have an idea how to do this?

View Replies !   View Related
Don't Insert Duplicate Rows
Hi, I need to insert rows into table1 from table2 and table3 but I don't want to insert repeated combinations of col2, col3. So, table1 has the primary key col2, col3.

This the table1:

create table table1(
col1 int not null,
col2 int not null,
col3 int not null,
constraint PK_table1 primary key (col2, col3)

This is my "insert" code:

SELECT table2.col1,table2.col2, table3.col3
FROM table2, table3
WHERE table2.col1 = table3.col1

Wich conditions shoud i add to this code?



View Replies !   View Related
How To CREATE Duplicate Rows
this may sound like a weird one, but i need to create duplicates of all rows that satisfy a condition.

using asp, i am able to select rows from a databate using a recordset, only to insert it straight back into the database, thus assigning it a new unique id.

but is there any one to perform this action just using sql?



View Replies !   View Related
Problem With (almost) Duplicate Rows

I have a table (mytable) with the following structure

docs int
field1 varchar(20)

the information in the table may look like this

docs field1
1 hello
2 hello
3 test
4 test
5 problem
6 problem

The docs column autoincrements and their is a unique constraint on it. The field1 column does not have any constraints on it.

how does on delete the duplicates without deleting both.

I can write a SQL statement to tell me what docs are dups, and what the field1 values are, but I cannot just delete one

Do I write a cursor? or is there an sql statement that would delete just one?


Steve Power

View Replies !   View Related


View Replies !   View Related
Deleting Some Of Duplicate Rows
This is an imaginary problem while discussing ROWID in ORACLE.

Consider a table without primary key, unique key, uniuqe index.
A row has inserted into the table many times.
I want to delete all but one dulicated rows. With any 'where' clause all rows(duplicated)
will be deleted. In ORACLE i can achieve this using ROWID as follows:

Delete from Table_name
where < all column values >
and ROWID <> ( Select max(rowid) from Table_name where < all column values > )

How can this be achieved in MS SQL Server 6.5 ?

According to Dr. Codd's Golden rules for RDBMS one is that
One should be able to reach each data value in the database by using
table name, row idenfication value and column name.

Does MS SQL Server 6.5 satisfy this requirement ?

Also How many of Dr. Codd's 13 Golden Rules for RDBMS does MS SQL Server 6.5
Satisfy? Which doesn't ?

Any discussion about Codd's Rules is welcome.

- Gunvant Patil

View Replies !   View Related
Remove Duplicate Rows
Hi Folks:
I'm in the process of data conversion. Before bcp to the actual table,
I create another intermediate table with same record structure, different name and without any indexes,foreign key constraint .... so that I can bcp the ASCII data set into that table with no error.
Now, is it possible to use one SQL statement to remove ALL DUPLICATE ROWS BUT THE LAST ONE. I meant, say that table t has 10 duplicate records on that fiel F1, I want to delete 9 of them but keep only one record only?
Thanks in advance for your time and advice.
David Nguyen

View Replies !   View Related
Deleting Duplicate Rows

I have problem in deleting duplicate rows. I have a identity column in my table, if I try to use correlatted sub query with Delete command it gives error.

The other problem I have is I have a date column in my table and update that column with current date and time. If use a query to fetch a records on a particular day , it does not return any rows

select * from rates where ch_date >='02/11/99' and ch_date<='02/11/99'

If I use convert also there is some other problems. Is there any way to force date checkings to be done excluding time.


View Replies !   View Related
Delete Duplicate Rows Using T-SQL
How do you delete duplicate rows in a table so only one row is left in the table, using T-SQL.

View Replies !   View Related
Duplicate Key But Unique Rows.
I have a large table that consists of the columns zip, state, city, county. The primary key "zip" has duplicates but the rows are unique.
How do I filter out only the duplicate zips.
Randy Garland

View Replies !   View Related

Copyright 2005-08, All rights reserved