在 SQL Server 中根据列值选择记录 [英] Selecting Records based on column value in SQL Server

查看:39
本文介绍了在 SQL Server 中根据列值选择记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表包含两列,其中包含以下输入记录.

I have table contains two columns having below input records.

样本输入记录

Column1         Column2
-----------------------
A                B
A                C
A                D
R                B 
R                D
S                E

在上述记录中,如果我给出 where 条件 Column2='D',它将显示在输出记录下方.

in the above records if i give where condition Column2='D' it will display below output records.

输出记录

Column1         Column2
-----------------------
A                B
A                C
A                D
R                B 
R                D

逻辑:在示例输入记录中,Column2='D' 包含两条记录.这两条记录包含 colum1 值,分别为A"和R".所以我想显示包含A"和R"的记录' 来自输入记录

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

假设如果给 where 条件 Column2='C' i 它将显示在输出记录下方.

Suppose if give where condition Column2='C' i it will display below output records.

输出记录

Column1         Column2
-----------------------
A                B
A                C
A                D

逻辑:在示例输入记录中 Column2='C' 包含一条记录.该记录包含A"的 column1 值.所以我想显示输入记录中包含'A'的记录

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

推荐答案

这会起作用:

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;

结果:

+---------+---------+
| Column1 | Column2 |
+---------+---------+
| A       | B       |
| A       | C       |
| A       | D       |
| R       | B       |
| R       | D       |
+---------+---------+

这篇关于在 SQL Server 中根据列值选择记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆