简体   繁体   English

从左表获取所有记录,并计算列值

[英]Get all the records from left table with computed column value

I have master table with structure : 我有结构的主表:

T1 T1

ID    Name
1     Cricket
2     Football
3     Golf

T2 T2

ID    T1-ID    SomeNumber
1     1        180
2     2        180
3     1        195
4     3        195

Column T1-ID is foreign ket fot table T1, ID column. T1-ID列是外来ket FOT表T1,ID列。 I want to get resultset for value in Somenumber for '180' like 我想获取结果集以Somenumber的值表示'180'例如

Output : 输出:

ID    Name        ComputedColumn
1     Cricket     True
2     Football    True
3     Golf        False

I have tried using Left-Joins, Case Statements but didnt get expected results. 我曾尝试使用Left-Joins,Case Statements,但未获得预期的结果。

You can use left join : 您可以使用left join

select t1.*,
       (case when t2.id is null then 'False' else 'True' end) as ComputedColumn
from t1 left join
     t2
     on t1.id = t2.t1_id and t2.somenumber = 180;

Actually, that assumes that a row with 180 occurs at most once for each id (as in your sample data). 实际上,这假设每个id最多有180行出现一次(如您的示例数据中一样)。 If such rows could occur multiple times, use case : 如果此类行可能发生多次,请使用case

select t1.*,
       (case when exists (select 1 from t2 where t1.id = t2.t1_id and t2.somenumber = 180)
             then 'True' else 'False'
        end) as ComputedColumn
from t1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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