我有这样的表:
product_id model date computers
----------------------------------------------------------------
12204 Asus 'random_date' :::aass:::ddff:::ddfd:::dfwr:::
12205 Acer 'random_date' :::ersz:::dfwqq:::bbs:::
12205 Acer 'random_date' :::ettww:::iwoeur:::iwerq:::
如您所见,product_id,模型可以复制。计算机字段包含当前行中的计算机数量。分隔符是:::。在我对它们进行分组(GROUP BY product_id)之后,第一个产品(12204)中有3台计算机,而其他产品(12205)中有6台计算机。所以查询结果必须是这样的:
GROUP(product_id) model count
-----------------------------------------
12204 Asus 4
12205 Acer 6
单个查询是否可以实现?或者我必须在后端代码(在我的情况下是python)中执行此操作?
(我无法修改表格,我正在处理其他人预先存在的表格)
修改更新了样本数据格式
答案 0 :(得分:4)
结合使用SUM
,ROUND
,LENGTH
,REPLACE
&计数字段为COUNT
,然后按product_id和model进行分组。
SELECT product_id, model,
SUM(ROUND ((LENGTH(computers) - LENGTH(REPLACE(computers, ":::", ""))) / LENGTH(":::"))) - count(product_id) AS count
FROM yourtable
GROUP BY product_id, model
输出
product_id model count
12204 Asus 4
12205 Acer 6
答案 1 :(得分:2)
尝试以下查询:
SELECT product_id, model,
SUM(1 + ((LENGTH(computers) - LENGTH(REPLACE(computers, ':::', ''))) / 3)) AS count
FROM products
GROUP BY product_id, model
点击以下链接查看正在运行的演示:
答案 2 :(得分:1)
SELECT product_id, model,
CAST(SUM(1 + ((LENGTH(TRIM(BOTH ":::" FROM computers)) - LENGTH(REPLACE(TRIM(BOTH ":::" FROM computers), ":::", ""))) / 3)) AS UNSIGNED) AS cnt
FROM products
GROUP BY product_id, model