简体   繁体   English

SQL查询划分字段

[英]SQL Query divide a field

数据库实例

I'd like, for each commercial, identified here by a code, to get the number of bills (in French: facture) being associated with him. 我想为每个通过代码标识的商业广告获取与他关联的账单数量(法语:制造)。

For example, here, with this part of the database, I'd like to have something like that: R08: 22; 例如,在这里,对于数据库的这一部分,我想拥有类似的东西:R08:22; R087: 19; R087:19; R11 : 3; R11:3; R00 : 3; R00:3; R062: 1; R062:1; R026: 1; R026:1;

A commercial code starts with a 'R' followed by a few digits and if the bill is associated with more than one commercial, a '|' 商业代码以“ R”开头,后跟几个数字,如果账单与多个商业广告相关联,则“ |” separates the codes. 分隔代码。 By the way, most of the bills are associated with only one commercial. 顺便说一下,大多数账单只与一个商业广告有关。

My problem is to do that only with SQL. 我的问题是只能使用SQL来做到这一点。 if it's too complicated, I'll do it with PHP. 如果太复杂了,我将用PHP来完成。

I hope my question is understandable and that you'll know how to help me. 我希望我的问题是可以理解的,并且您会知道如何帮助我。

An other example of data: 另一个数据示例:

R015        15040205
R012        14250123
R012|R038   14250123
R015|R012   14250123
R005        14250123

I'd like a query that returns: 我想返回一个查询:

R005        1
R038        1
R015        2
R012        3

actually, I would like a query that counts the number of occurrences of each code. 实际上,我想查询一个查询每个代码出现次数的查询。 The second data doesn't matter 第二个数据没关系

If you have at most two codes (as in your sample data), then you can use substring_index() : 如果您最多有两个代码(如示例数据中所示),则可以使用substring_index()

select code, count(*)
from ((select substring_index(code_commercial, '|', 1) as code
       from t
      ) union all
      (select substring_index(code_commercial, '|', -1)
       from t
       where code_commercial like '%|%'
      )
     ) c
group by code;

The more important point is that your data model is really, really, really bad. 更为重要的一点是,您的数据模型确实非常糟糕。 You should be fixing it. 您应该修复它。 SQL is not designed to store multiple values in a single column -- or to use strings to store this type of data. SQL并非设计为在单个列中存储多个值,也不设计为使用字符串来存储此类数据。

You want a junction table, with separate rows for each code. 您需要一个联结表,每个代码都有单独的行。 Then your query would be easier to write and run faster. 这样,您的查询将更易于编写和运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM