user3281388
user3281388

Reputation: 267

Make only 1 column distinct in SQL?

Is there a way to make one column distinct? I have a query that takes the first two columns and sums them together for the third column. In row 2 we have 2+1=3; then in row 4 we have 1+2=3. Is there a way to put a restriction/constraint on my statement so that I can eliminate those rows?

This is what I have so far:

SELECT TableA.n AS ColumnA, TableB.n AS ColumnB, (TableA.n + TableB.n) as [Sum]
FROM MyTable AS TableA CROSS JOIN MyTable AS TableB
WHERE TableA.n <= 3 AND TableB.n <= 3 

I thought perhaps I could do this but it doesn't work: distinct (TableA.n + TableB.n) as [Sum]

enter image description here

Using Microsoft Sql Server

Upvotes: 1

Views: 76

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

If I understand correctly, you can require that columnA < columnB:

SELECT TableA.n AS ColumnA, TableB.n AS ColumnB, (TableA.n + TableB.n) as [Sum]
FROM MyTable AS TableA CROSS JOIN
      MyTable AS TableB
WHERE TableA.n < TableB.n AND
      TableA.n <= 3 AND TableB.n <= 3 ;

Upvotes: 3

Related Questions