Selecting Records based on column value in SQL Server

☆樱花仙子☆ 提交于 2019-12-14 02:38:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!