首先,对不起标题是否具有描述性,但我不知道该如何描述我想要实现的目标。我的数据库系统是SQL Server 2008 R2。问题如下:
我有两个表A和B,它们之间具有1 .. *关系,由表A的ID链接。我想根据此规则用表B的单个值查询表A:
如果有的话,“ BALL”,“ PARTIAL”,“ NONE”是表B中唯一可用的值。
有人可以帮助我做到这一点吗?谢谢您的帮助
答案 0 :(得分:3)
假设表A的列称为id
,表B的列称为a_id
和value
,则可以结合使用outer join
和某些列group
正在向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()
比较表B中的值非常简单,应该可以自我解释-如果没有,只需将min(b.value)
和max(b.value)
添加到您的表中select语句查看输出的值,以帮助可视化。要理解的棘手部分是“部分”规则。 case语句的该部分评估表B中每一行的值,如果它是“ partial”,那么它将为该行返回值“ 1”。查询评估了该组的所有B行之后,它选择max()
值以查看是否返回了“ 1”。
答案 1 :(得分:2)
您可以进行汇总,然后使用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