T-SQL查找具有至少一个特定列值的行

时间:2018-08-27 22:53:58

标签: sql-server tsql

数据集

Key           Stage     balance   ForeignKey
---------------------------------------------
11805008       ABC         50      123
11805008       DEF          0      123  
14567898       DEF        100      456 

查询到目前为止

Select key, two.Stage, two.balance 
from table_a one, table_b two
where one.ForeignKey = two.foreignKey

我正在寻找密钥,阶段和平衡,其中密钥具有ABC和其他阶段。如果密钥不具有阶段ABC,则它不应返回该密钥的任何行。但是,如果该键具有“ ABC”阶段,则应返回该键的所有行

Key           Stage     balance   ForeignKey
11805008       ABC        50       123
11805008       DEF        0        123  

3 个答案:

答案 0 :(得分:0)

您可以使用IN子句获取具有至少一个ABC阶段的所有键。另外,请使用更现代的内部联接语法。

SELECT one.key, two.Stage, two.balance
FROM table_a one
INNER JOIN table_b two ON one.ForeignKey = two.foreignKey
WHERE key IN (
  SELECT key
  FROM table_a
  INNER JOIN table_b ON table_a.ForeignKey = table_b.foreignKey
  WHERE table_b.stage = 'ABC')

答案 1 :(得分:0)

首先,学习使用正确的JOIN语法。

第二,您可以使用窗口功能来做到这一点:

select key, stage, balance
from (Select key, two.Stage, two.balance,
             sum(case when two.stage = 'ABC' then 1 else 0 end) over (partition by key) as num_abc
      from table_a one join
           table_b two
           on one.ForeignKey = two.foreignKey
     ) t
where num_abc > 0;

答案 2 :(得分:0)

Select key, two.Stage, two.balance 
from table_a one
inner join table_b two
on one.foreignKey = two.foreignKey
where exists (
  select 1 from table_b x 
  where  x.foreignKey=one.foreignKey
  and x.Stage='ABC' )

我只能假设您的原始数据是什么。该语句适用于我的演示,请参见此处:http://rextester.com/SUTS17842