首先,对不起,如果标题不是很具描述性,但我不知道如何描述我想要实现的目标。我的数据库系统是SQL Server 2008 R2。问题如下:
我有两个表,A和B,有一个1 .. *关系,由表A的Id链接。我想使用表B的单个值查询表A,具体取决于此规则:
“ALL”,“PARTIAL”,“NONE”是表B中唯一可用的值,如果有的话。
任何人都可以帮我搞定吗?谢谢您的帮助
假设表A有一个名为id
的列,而表B有一个名为a_id
和value
的列,你可以使用outer join
和一些group
ing的组合来为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”。
您可以聚合然后使用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