问题
I have table contains two columns having below input records.
Sample Input Records
Column1 Column2
-----------------------
A B
A C
A D
R B
R D
S E
in the above records if i give where condition Column2='D' it will display below output records.
Output Records
Column1 Column2
-----------------------
A B
A C
A D
R B
R D
Logic:In the Sample input records Column2='D' contains two records.These two records contain the colum1 values as 'A' and 'R'.so i want to display the records which contains 'A' and 'R' from the input records
Suppose if give where condition Column2='C' i it will display below output records.
Output Records
Column1 Column2
-----------------------
A B
A C
A D
Logic: in the sample input records Column2='C' contains one record. This record contains the column1 value of 'A'. So I want to display the records which contain 'A' from the input records
回答1:
This will work:
CREATE TABLE #temp
(
Column1 CHAR(1) ,
Column2 CHAR(2)
);
INSERT INTO #temp ( Column1 ,
Column2 )
VALUES ( 'A', 'B' ) ,
( 'A', 'C' ) ,
( 'A', 'D' ) ,
( 'R', 'B' ) ,
( 'R', 'D' ) ,
( 'S', 'E' );
SELECT *
FROM #temp
WHERE Column1 IN ( SELECT Column1
FROM #temp
WHERE Column2 = 'D' );
DROP TABLE #temp;
Result:
+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A | B |
| A | C |
| A | D |
| R | B |
| R | D |
+---------+---------+
来源:https://stackoverflow.com/questions/51291064/selecting-records-based-on-column-value-in-sql-server