【问题标题】:How do I solve and write this query?如何解决和编写此查询?
【发布时间】:2020-10-02 06:25:20
【问题描述】:

我有三个看起来像这样的表:

Table1 有 1 行数字:

123
124
125
126
127

等等

Table2 与 Table1 类似,但元素更多:

123
124
125
158
152
175

等等

主表有很多行,这是我挣扎的地方:

select
   a,
   b,
   c,
   if HIT in Table1 and NO HIT in Table2 then '1G'
   else if HIT in Table1 AND HIT in Table2 then '2G'
   else d,
   e,
   f,
   g,
   etc
from Table3

解释得有点乱,但我不知道怎么说更好……对不起!

希望你们中的一些人可以帮助我解决这个问题!

-盖尔 A.

【问题讨论】:

  • "Table1 有 1 行数字:" 行?还是专栏?给出适当的样本。也请从他们那里添加你想要的输出。
  • “主表”是Table3?您想要 Table3 中的所有行以及基于其他表中“命中”的某种计算值吗? “命中”是指基于匹配哪些列而存在的行?
  • @mkRabbani: 1 列和很多行,正确.. 我写的时候头晕目眩
  • @SMor:我很不擅长解释,但是如果 a 中存在值而不 b 中存在值,我想为该特定列指定文本,然后如果 a 和 b 中都存在另一个值。如果不存在这样的值,则使用上一个列中的任何值

标签: sql sql-server if-statement select case


【解决方案1】:

您可以使用两个LEFT JOIN。例如:

select
  a,
  b,
  c,
  case when b.col is not null and c.col is null then '1G'
       when b.col is not null and c.col is not null then '2G'
       else d end,
  e,
  f,
  g,
  etc
from table3 a
left join table1 b on b.col = a.col
left join table2 c on c.col = a.col

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2015-08-14
    • 1970-01-01
    • 2021-01-15
    • 2011-10-30
    • 1970-01-01
    • 2013-02-01
    • 2012-02-29
    • 2012-01-19
    相关资源
    最近更新 更多