有两个表,库存和批次,我使用库存表来保存项目的描述,包括项目的类别,按字段inventory.type过滤为inventory.type ='isInventoryItem'或inventory.type ='品种'和inventory.invid为TEXT,以及用于持有批次的批量表。
invid | type
Sugraone | Variety
Autumn Royal | Variety
Flame | Variety
Summer Royal | Variety
Red Globe | Variety
和它喜欢的项目:
invid | type
Sugraone 19#Pouch Free Bird Ctn B | isInventoryItem
Red Globe 21#PlainSO Chelan Starr 7L Sty | isInventoryItem
Flame 19#Pouch SO2 Puro Filete 5L Styro A | isInventoryItem
我希望能够从库存中选择type ='Variety',并使用LIKE为inventory.invid按类别计算批次表中的实例我试试这个:
SELECT COUNT(inventory.*) AS lots, invid FROM lots
INNER JOIN inventory ON lots.inventory_id = inventory.inventory_id
WHERE invid ILIKE ANY (SELECT '%' || invid || '%'
from inventory WHERE type ='isInventoryItem') GROUP BY invid;
没有成功,我想要这个输出:
invid | count
Sugraone | 5
Autumn Royal | 6
Flame | 3
Summer Royal | 7
Red Globe | 23
这样做的方法是什么。
编辑:我添加了一个视图(items_view),仅列出已经过滤的invid AS名称,只获取要搜索类别的项目列表以简化:
name
Flame 19#Pouch Acosta Produce Ctn B
Flame 19#Pouch Acosta Produce Ctn B
Flame 19#Pouch SO2 J.A.P. Black 5L Styro B
Red Globe 21#PlainSO Chelan Starr 7L Sty
Red Globe 21#PlainSO Chelan Starr 7L Sty
Sugraone 19#Pouch Free Bird Ctn B
Summer Royal 19#Pouch SO2 SF White Od 5L Styro A
Summer Royal 19#Pouch Top Gun Cnt A
我可以得到这样的类别列表:从库存中选择inid,其中type ='Variety',我得到如下列表:
invid
--------------
Sugraone
Autumn Royal
Flame
Summer Royal
Red Globe
现在的问题是如何使用LIKE循环列出此类别列表,以计算库存项目列表并获得如下结果
invid | count
Sugraone | 1
Autumn Royal | 2
Flame | 3
Summer Royal | 2
Red Globe | 2
答案 0 :(得分:2)
您使用invid
行type = 'isInventoryItem'
作为模式。而是使用type = 'Variety'
作为模式的行:
SELECT invid
, COUNT(inventory.*) AS lots
FROM lots
INNER inventory
ON lots.inventory_id = inventory.inventory_id
WHERE inventory.type = 'isInventoryItem'
AND invid ILIKE ANY
(
SELECT '%' || invid || '%'
FROM inventory
WHERE type = 'Variety'
)
GROUP BY
invid
作为旁注,请考虑学习database design and normal forms。您可能应该有一个单独的库存类别表,而不是在库存表本身中包含类别。