views:

1094

answers:

4

I have very simple problem that I can't solve. I need to do something like this:

select distinct * from (1, 1, 1, 2, 5, 1, 6).

Anybody can help??

+3  A: 

Simplest way I know of would be to use a UNION to get the distinct values.

select 1
union select 1
union select 1
union select 2
union select 5
union select 1
union select 6
Lieven
no, no, I have a list of several hundreds of values, manually it would be torture
Eedoh
where does that list come from? It might be way easier to just copy /paste that list in Excel and extract the distinct values there using a simple crosstab.
Lieven
btw, find and replace might also take you a long way. Replace every comma with *union select*, add a select in front and you should have a working query cfr the union I showed.
Lieven
it comes as a text file from one of our clients. It's totally unformated (it's a single, very long line of text), but it may be possible to do so in Excel. But it's not practical for me, because I will need to use theese values in my sql query. It's not convenient to do so every time I need to run a query
Eedoh
this stuff with replacing commas with select union works like a charm Thanks a lot :)
Eedoh
no problem. [<sigh> Comments must be at least 15 characters in length.]
Lieven
+1  A: 
  • If you want to select only certain values from a single table you can try this

    select distinct(*) from table_name where table_field in (1,1,2,3,4,5)

    eg: select first_name,phone_number from telephone_list where district id in (1,2,5,7,8,9)

  • if you want to select from multiple tables then you must go for UNION.

  • If you just want to select the values 1, 1, 1, 2, 5, 1, 6 then you must do this

    select 1 union select 1 union select 1 union select 2 union select 5 union select 1 union select 6

Anirudh Goel
I don't need to select from a table, but from this list of values (in brackets). That's the main problem (selecting from comma separated array of values, not from a table)
Eedoh
that case, like we have DUAL table in Oracle, you can make use of the same. But since there is no DUAL then you will have to go the union way. You can try another method, as you mentioned you have comma separated array of values, why don't you insert them to a table and then use a neat sql select query, instead of using so many sql unions.
Anirudh Goel
+2  A: 

This works on SQL Server 2005 and if there is maximal number:

SELECT * 
FROM
  (SELECT ROW_NUMBER() OVER(ORDER BY a.id) NUMBER
  FROM syscomments a
  CROSS JOIN syscomments b) c
WHERE c.NUMBER IN (1,4,6,7,9)
LukLed
+1 neat but it is limited to the amount of rows in syscomments cross joined with itself. In my case to 294849. (and you forgot distinct.)
Lieven
You can cross join once more, but replacing commas is much faster solution.
LukLed
Yeah, this way is good also, but I prefer Lieven's solution, because of simplicity.
Eedoh