试试这个:
select
Bill_items.billcode
,max(cast(CheckFlag as int)) as flagSet
from Bill_items
join Linked_items
on Bill_items.billcode = Linked_items.Bill_Code
join inventoryitems
on Linked_items.Item_code = inventoryitems.ItemCode
group by
Bill_items.billcode
如果您需要在不包含库存项目的情况下包含 Bill_items,请尝试以下操作:
select
Bill_items.billcode
,max(isnull(cast(CheckFlag as int),0)) as flagSet
from Bill_items
left join Linked_items
on Bill_items.billcode = Linked_items.Bill_Code
left join inventoryitems
on Linked_items.Item_code = inventoryitems.ItemCode
group by
Bill_items.billcode
这是加入账单项目的派生版本
select
Bill_items.*
,isnull(_CheckFlags.flagSet,0) as flagSet
from Bill_items
left join (
select
Linked_items.Bill_Code
,max(cast(CheckFlag as int)) as flagSet
from Linked_items
join inventoryitems
on Linked_items.Item_code = inventoryitems.ItemCode
group by
Linked_items.Bill_Code
) _CheckFlags
on Bill_items.billcode = _CheckFlags.Bill_Code
试试这个没有 CAST 的方法:
select
Bill_items.*
,isnull(_CheckFlags.flagSet,0) as flagSet
from Bill_items
left join (
select
Linked_items.Bill_Code
,CheckFlag as flagSet
from Linked_items
join inventoryitems
on Linked_items.Item_code = inventoryitems.ItemCode
where CheckFlag = 1
group by
Linked_items.Bill_Code
,CheckFlag
) _CheckFlags
on Bill_items.billcode = _CheckFlags.Bill_Code