简体   繁体   中英

Sql view based on a flag in column

I am struck in a very hectic situation in SQL. I have a table with the columns (name,is_right) and i want to get a view like:

Wrong Name|| Right Name 
Jass      ||  Jasu  

for the table

Name  || is_right
Jass  || 0  
Jasu  || 1

I am trying to find a solution for this but nothing works. Please help me or guide me through any example so that i can pick it up.

I will assume you have a memberID for the users. Please assume @table is your current table with the user information. I assume each memberID only have one value 0 and one value 1

declare @table table
(
  memberID nvarchar(10),
  name nvarchar(10),
  is_right integer
 )

 insert into @table values ('A','Jass',0);
 insert into @table values ('A','Jasu',1);
 insert into @table values ('B','Pata',0);
 insert into @table values ('B','Peter',1);

 select distinct 
 (select B.name from @table B where b.is_right = 0 and B.memberID = A.memberID) as 'wrong name',
 (select C.name from @table C where c.is_right = 1 and C.memberID = A.memberID) as 'right name'
 from @table A

this what it return

wrong name| right name

Jass | Jasu

Pata | Peter

Use 2 sub query's. These will need to be linked with an ID to linked them too the main query but you haven't provided that data.

SELECT 
(SELECT Name FROM yourtable WHERE is_right = 0) AS Wrong_Name,
(SELECT Name FROM yourtable WHERE is_right = 1) AS RIGHT_NAME
FROM yourtable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM