SQL 查询值取决于其他链接 table 多个值

SQL query value depending on other linked table multiple values

首先,如果标题不是很清楚,我很抱歉,但我不知道如何描述我想要实现的目标。我的数据库系统是 SQL Server 2008 R2。问题如下:

我有两个 table,A 和 B,具有 1..* 关系,由 table A 的 ID 链接。我想查询 table A 的单个值 table B 取决于此规则:

  1. 如果tableB中没有匹配的记录则写入"red"
  2. 如果tableB中的所有记录都是"NONE"则写"red"
  3. 如果tableB中的所有记录都是"ALL"则写"green"
  4. 如果我们有"NONE"和"ALL"的混合,那么写"yellow"
  5. 如果 table B 中的任何匹配行是 "PARTIAL" 则写入 "yellow"

"ALL"、"PARTIAL"、"NONE" 是 table B 中唯一可用的值,如果有的话。

谁能帮我搞定?感谢您的帮助

假设 table A 有一个名为 id 的列,而 table B 有一个名为 a_idvalue 的列,您可以使用outer join 和一些 grouping 的组合以向 case 语句提供一些聚合值。

select
    a.id,
    case
        when (max(b.a_id) is null) then "red" -- No match found
        when (min(b.value) = "NONE" and max(b.value) = "NONE") then "red" -- All B values are "NONE"
        when (min(b.value) = "ALL" and max(b.value) = "ALL") then "green" -- All B values are "ALL"
        when (max(case when (b.value = "PARTIAL") then 1 else 0 end) = 1) then "yellow" -- At least one B value contains "PARTIAL"
        when (max(case when (b.value = "NONE") then 1 else 0 end) = 1 and max(case when (b.value = "ALL") then 1 else 0 end) = 1) then "yellow" -- A mix of "NONE" and "ALL"
        else "Undefined"
    end
from
    table_a a
    left outer join table_b b
        on (a.id=b.a_id)
group by
    a.id

这里的大部分逻辑都在 case 语句中。使用 min()max() 来比较 table B 中的值非常简单,应该是不言自明的——如果没有,只需添加 min(b.value)max(b.value) 到您的 select 语句以查看输出的值,以帮助可视化它。更难理解的部分是 "partial" 的规则。 case 语句的那部分评估了 table B 中每一行的值,如果它是 "partial",那么它 returns 该行的值“1”。在查询评估了该组的所有 B 行后,它 select max() 值以查看是否曾返回“1”。

您可以聚合然后使用 CASE 子句对案例进行分类,如:

select
  a.*,
  case when x.id is null then 'red' -- rule #1
       when x.partial > 0 then 'yellow' -- rule #5
       when x.none > 0 and x.all = 0 then 'red' -- rule #2
       when x.none = 0 and x.all > 0 then 'green' -- rule #3
       when x.none > 0 and x.all > 0 then 'yellow' -- rule #4
       else 'undefined case' -- safety net, for future changes
  end as color
from a
left join (
  select
    a.id,
    sum(case when b.state = 'NONE' then 1 end) as none,
    sum(case when b.state = 'ALL' then 1 end) as all,
    sum(case when b.state = 'PARTIAL' then 1 end) as partial
  from a
  join b on b.a_id = a.id
  group by a.id
) x on a.id = x.id