0

我有一个名为 Customers 的表,其中包含一个 CustID 列和另一个名为 ProductCode 的列。有 33 种可能的产品(编号为 1 到 33),每个客户可以拥有任何产品组合。每个客户都有一行,每个客户拥有的所有产品都显示在 ProductCode 列中,中间有一个空格,即:

CUSTID     PRODUCTCODE  
------     -----------

001        3 12 18 22 32  
002        9 6 18 36  
003        3 6 7 26  
004        9 11 33   
005        6 21 28 29 30 31  
006        1 3 6 21 30 31  

我需要能够对每个产品进行计数并添加代码的文本描述:

ProdCode    Description       Count  
~~~~~~~~    ~~~~~~~~~~~       ~~~~~  
1           Lawnmower         1  
3           Spade             3  
6           Clippers          4  
etc

谢谢!

4

3 回答 3

0

一种解决方案是将您的架构更改为具有两列:-

1) 客户 ID 2) 产品 ID

所以数据看起来像这样:-

cust_id| product_id

001    | 3
001    | 6
002    | 9

……

所以现在在mysql查询中你可以使用查询

Select product_id,count(*) as num_products from table_name group by product_id;

希望这可以帮助。

如果你不能改变你的模式,那么你必须获取数据并在你的脚本语言中你必须按照你的意愿处理它。

于 2013-10-07T08:30:04.073 回答
0

尝试这个:

CREATE TABLE ord (custid VARCHAR(3), productcode VARCHAR(40));

INSERT INTO ord VALUES ('001', '3 12 18 22 32');
INSERT INTO ord VALUES ('002', '9 6 18 36');
INSERT INTO ord VALUES ('003', '3 6 7 26');
INSERT INTO ord VALUES ('004', '9 11 33');
INSERT INTO ord VALUES ('005', '6 21 28 29 30 31');
INSERT INTO ord VALUES ('006', '1 3 6 21 30 31');

CREATE TABLE products (code VARCHAR(2));

INSERT INTO products VALUES ('3');
INSERT INTO products VALUES ('12');
INSERT INTO products VALUES ('18');
INSERT INTO products VALUES ('22');
INSERT INTO products VALUES ('32');
INSERT INTO products VALUES ('9');
INSERT INTO products VALUES ('6');
INSERT INTO products VALUES ('31');

CREATE TABLE ord_prod (code VARCHAR(2), count_of_products INT) AS
  SELECT p.code, 
        (SELECT COUNT(1)
           FROM ord o
         WHERE INSTR(CONCAT(' ', o.productcode, ' '), CONCAT(' ', p.code, ' ')) > 0) AS count_of_products
    FROM products p;

查看 SQLFiddle:http ://sqlfiddle.com/#!2/a7f94/1

根据需要更改类型,添加其余产品,添加描述等。

于 2013-10-07T08:56:42.947 回答
0

永远,永远,永远不要在一列中存储多个值!

正如你现在看到的,这只会导致问题。请使用附加表规范您的数据库结构

customer_products
CUSTID     PRODUCTCODE  
------     -----------
001        3
001        12
001        18
---
002        9
002        6
...

然后,您可以PRODUCTCODE从表中删除该列customer

于 2013-10-07T08:25:26.850 回答