我在表格中有以下数据:
condId condGrpId condVal Flag
1 1 true 1
2 1 false 1
3 1 true 0
1 2 true 1
4 2 false 1
1 3 true 1
3 3 true 1
上表表示条件集合的条件组。 " condVal"列表示条件是真还是假。"标记"列表示条件的运算符。如果标志值为1,则相应的条件将用作" AND"条件组中的条件,否则" OR"从上表中,我想获取所有条件为真的" condGrpId" s取决于" Flag&# 34; seg CondGrpId" 1"有3个条件。对于ist和第2行,Flag值为" 1"。这意味着第1行和第2行的" condVal将由AND运算符连接。条件组中第3行的标志值为" 0"。这意味着它将被连接用" OR"运营商。
我想获取" condGrpId" s以了解应用运算符的真实条件。 如何编写通用查询来获取CondGrpIds?
答案 0 :(得分:1)
试试这个:
with add_bool as
(
select condId, condGrpId, condVal, Flag
, case condVal when 'true' then 1 else 0 end [condBool]
, row_number() over(partition by condGrpId order by condId) [row_id]
from #your_table
)
, base as
(
select [row_id], condId, condGrpId, condVal, Flag, [condBool], 1 [counter]
from add_bool
where condId = 1
union all
select t.[row_id], t.condId, t.condGrpId, t.condVal, t.Flag
, case t.flag
when 1 then t.[condBool] & b.[condBool]
else t.[condBool] | b.[condBool]
end
, [counter] + 1
from add_bool t
join base b on b.condGrpId = t.condGrpId
and b.[row_id] + 1 = t.[row_id]
where t.condId > 1
)
, ranked as
(
select *
, row_number() over(partition by condGrpId order by [counter] desc) [is_max_counter]
from base
)
select condGrpId, condVal
from ranked
where [is_max_counter] = 1
结果
condGrpId condVal
-------------------
1 true
2 false
3 true
答案 1 :(得分:0)
检查一下......
select condGrpId,flag ,condVal
from tbl
where condVal='true' group by condGrpId ,flag,condVal