Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Distinct values from single table

Author  Topic 

Chirag23
Starting Member

13 Posts

Posted - 2013-05-30 : 03:51:33
I have a single table that has two columns.

__A__|__B___
12345 | 999
12345 | 818
11111 | 999
12345 | 999
12345 | 999
12345 | 818
11111 | 999

I want to filter the results to return the following instead:

__A__|__B___
12345 | 999
12345 | 818
11111 | 999

DISTINCT queries don't work as I'm trying to find distinct results for a combination of both columns and not just one.

Any ideas?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-30 : 03:57:43
it will work

SELECT DISTINCT A,B
FROM Table


Unless you've additional columns which you want to include in the resultset having unique values in them

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Chirag23
Starting Member

13 Posts

Posted - 2013-05-30 : 04:50:35
Thanks for quick response, Apologies for not being clear however there are additional values in this table.

__A__|__B___| C
12345 | 999 | Steve
12345 | 818 | Ben
11111 | 818 | Steve

In this example, I'd like to run a query where I can insert a new value in this table where I add the distinct value and then 'Ben' in the third column.

__A__|__B___| C
12345 | 999 | Steve
12345 | 818 | Ben
11111 | 818 | Steve
-----------------------
11111 | 818 | Ben
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-30 : 04:54:15
So in all cases you need to insert a value for Ben with B=818 if one not exists already for the group?

INSERT YourTable
SELECT A,818,'Ben'
FROM YourTable t
WHERE NOT EXISTS (SELECT 1
FROM YourTable
WHERE A = t.A
AND B= 818
ABD C= 'Ben'
)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Chirag23
Starting Member

13 Posts

Posted - 2013-05-30 : 07:11:19
Ok thanks. It works
Go to Top of Page

Chirag23
Starting Member

13 Posts

Posted - 2013-05-30 : 07:11:20
Ok thanks. It works
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-30 : 08:27:40
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -