-3

I have a table that has 3 columns: - ID - FROM - TO And i have data like that

-----------------------
ID   |   FROM   |   TO
1    |   2      |   1
2    |   5      |   1
3    |   7      |   1
4    |   2      |   1
5    |   2      |   1
6    |   9      |   1
7    |   3      |   1
8    |   4      |   1
9    |   5      |   1

I would like to create a query that selects all rows where TO = 1 and i don't want to display rows that was previously retrieved, for example i have multiple rows where FROM = 2 and TO = 1, i just need to retrieve that row only once.

My table doesn't really look like this but i am giving a small example because my aim is to collect all FROM numbers but without any redundancy.

BOSS
  • 1,828
  • 11
  • 34
  • 60

4 Answers4

1

Use DISTINCT

SELECT DISTINCT from,to FROM yourTable WHERE to = 1

Declan_K
  • 6,726
  • 2
  • 19
  • 30
1

use distinct keyword

select distinct m.from,m.to from mytable as m;
danisius
  • 597
  • 1
  • 5
  • 19
1

You just have to group by the columns you want to display:

select [from] from mytable group by [from]

If you want to see how many froms you have all you have to do is:

select [from], count(*) from mytable group by [from]

You could use distinct but it would slower than group by but require more memory.

Please read here if you want an explanation on the difference between group by and distinct: Huge performance difference when using group by vs distinct

Community
  • 1
  • 1
Avitus
  • 15,640
  • 6
  • 43
  • 53
1

Not sure what exactly you meant select distinct [FROM] from TableName where [TO] = 1

OR

may be you need single row for every distinct [FROM] value for given [TO] ?

;with cte as (
    select ID, [FROM], [TO],
        rn = row_number() over (partition by [FROM] order by ID)
    from TableName
    where [TO] = 1
)
select ID, [FROM], [TO]
from cte
where rn=1
i-one
  • 5,050
  • 1
  • 28
  • 40