user3959104
user3959104

Reputation: 65

How to return same data in different column?

I have few columns as below:

  column1 column2 column3 column4
  ID123   Apple   Red     Apple
  ID456   Apple   Blue    Apple
  ID987   Pear    Blue    Apple
  ID899   Pear    Blue    Apple

I wanted to pull rows where column2 = column4 as below:

  column1 column2 column3 column4
  ID123   Apple   Red     Apple
  ID456   Apple   Blue    Apple

I tried:

  select column1,column2,column3,column4
  where column2=column4

But no result are returned.

Where is my mistake?

Upvotes: 1

Views: 63

Answers (1)

fox909a
fox909a

Reputation: 391

As Recommend to you if the collation is Case Sensitive then you should make the columns all the same by using either UPPER or LOWER i would also do a replace for any spaces.

Example

 CREATE TABLE #temp1
(
    column1 NVARCHAR(255),
    column2 NVARCHAR(255),
    column3  NVARCHAR(255),
    column4 NVARCHAR(255)
)

INSERT INTO #temp1 VALUES('ID123','Apple','Red',' Apple')
INSERT INTO #temp1 VALUES('ID456','Apple','Blue','Apple')
INSERT INTO #temp1 VALUES('ID987','Pear','Blue','Apple')
INSERT INTO #temp1 VALUES('ID899','Pear','Blue','Apple')

SELECT * FROM #temp1
WHERE REPLACE(UPPER(column2), ' ', '' ) = REPLACE(UPPER(column4), ' ', '' )

drop table #temp1

Upvotes: 1

Related Questions