我正在使用一个数据集,该数据集是从非常复杂的视图中返回的,该视图具有多个子选择,并在一个庞大而复杂的数据库中与多个表联接。
每个记录的结构如下:
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 3, qtyPlaceholderKey = 1, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 10, qtyPlaceholderKey = 3, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 9, qtyPlaceholderKey = 2, color = blue.
因此,对于每种颜色和MainValue值,都有多个记录。我需要根据实际数量设置每个qtyPlaceholder的值,其中qtyPlaceholderKey会告诉我要输入什么值,并且仅从多个记录中派生一个记录,以便最终的单个记录如下所示:
MainValue = XXTS10, qtyPlaceholder1 = 3, qtyPlaceholder2 = 9, qtyPlaceholder3 = 10, color = blue.
我知道这些年来我已经做过数百次了,但是我只是在脑子里创建适当的循环结构和条件,以创建多个记录中的单个记录,并将值正确映射到占位符。尝试在PHP中完成此操作,但是重新检查视图并查看它是否可以调整可能是个好主意,但是我真的不愿意走这条路。
有什么建议么?
您可以使用条件聚合在SQL中执行此操作。这是select
查询的一种形式:
select MainValue,
max(case when qtyPlaceholderKey = 1 then actualQty end) as qtyPlaceholder1,
max(case when qtyPlaceholderKey = 2 then actualQty end) as qtyPlaceholder2,
max(case when qtyPlaceholderKey = 3 then actualQty end) as qtyPlaceholder3,
color
from complexview v
group by MainValue, color;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句