views:

155

answers:

3

I need to select 3 columns from a table, but I need each value from any column to be unique in the resultset for this column.

This query:

SELECT DISTINCT TOP 10 a, b, c
FROM   x

will return 10 distinct sets.

How do I do it?

A: 

does this question not give you what you want?

Sam Holder
+1  A: 

I don't know if this is possible in one shot. I would do this by creating a table variable.

DECLARE @Results TABLE
(
  a varchar(100),
  b varchar(100),
  c varchar(100)
)
INSERT @Results(a)
SELECT DISTINCT a FROM myTable

INSERT @Results(b)
SELECT DISTINCT b FROM myTable

INSERT @Results(c)
SELECT DISTINCT c FROM myTable

SELECT a,b,c FROM @Results
ichiban
+4  A: 
WITH q AS
        (
        SELECT  a, b, с, ROW_NUMBER() OVER (ORDER BY a, b, c) AS rn
        FROM    mytable
        )
SELECT  TOP 10 a, b, c
FROM    q q1
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    q
        WHERE   q.rn < q1.rn
                AND q.a = q1.a
        )
        AND NOT EXISTS
        (
        SELECT  1
        FROM    q
        WHERE   q.rn < q1.rn
                AND q.b = q1.b
        )
        AND NOT EXISTS
        (
        SELECT  1
        FROM    q
        WHERE   q.rn < q1.rn
                AND q.c = q1.c
        )
Quassnoi
That's some beautiful tsql +1
ichiban
@ichiban: thanks :) I'm gonna make today's post in my blog out of it
Quassnoi