1

I am writing a query in SQL server2005. This is returning me a duplicate rows in the result. Can i eliminate this duplication with a particular column as the key?

Vinod
  • 31,933
  • 35
  • 96
  • 119

6 Answers6

9

You can eliminate complete duplicate rows using the DISTINCT keyword. If there is some key column that is a duplicate but the rest of the columns are not, then you would have to use aggregate functions and a GROUP BY clause to explain to SQL Server what data you do want returned.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
6

SELECT DISTINCT will eliminate duplicate rows.

Bliek
  • 466
  • 3
  • 7
3

You can use SELECT DISTINCT to eliminate duplicates, as has been advised in other comments, and it may work well enough for now, but you may be begging for future trouble. All too frequently, if you cannot get a unique result without SELECT DISTINCT, your database model has been denormalized too far, and your queries can get bogged down by retrieving and then eliminating a large number of duplicates. (However, of course, normalizing an existing database schema is rarely trivial...)

Without more information on the schema and the query it's impossible to tell whether SELECT DISTINCT is an acceptable workaround, or whether there simply is a better join statement.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
0

It's possible that your result contains both an associative and a numeric array.

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
0

If you just want one column:

SELECT DISTINCT MyColumn FROM MyTable;

If you want a variety of columns, possibly returning a maximum or sum, try grouping it:

SELECT MyFirstColumn, MySecondColumn, MAX(SomeDate) AS MaxDate, SUM(Amount) AS TotalAmount 
FROM MyTable 
GROUP BY MyFirstColumn, MySecondColumn;
Chris Latta
  • 20,316
  • 4
  • 62
  • 70
  • Multiple columns with distinct should be ok as well. As long as aggregate operations are not needed. – Aleksi Yrttiaho Sep 23 '08 at 08:54
  • but will i be able to do a groupby on the results of a execution of stored procedure? like exec sp_depends tbl_control_quarterly_milestone – Vinod Sep 23 '08 at 09:09
0

As you have pointed out in the comments, you are using a stored procedure. One way to handle this case is to create a temporary table which you populate using the stored procedure. Then select the results from the temporary table and prune the duplicates with either SELECT DISTINCT or GROUP BY.

Aleksi Yrttiaho
  • 8,266
  • 29
  • 36