简体   繁体   English

SQL:计算每行的出现次数

[英]SQL: count occurrences for each row

I have an SQL table called Codes with a primary column code of type String.我有一个名为Codes的 SQL 表,其主列code为 String 类型。 I also have another table called Items with a column codestring also of type String.我还有另一个名为Items表,其中的列codestring字符串也是 String 类型。 This entry always contains a string with some of the codes of the above table separated by spaces.此条目始终包含一个字符串,其中上表的某些代码以空格分隔。 Now I want to get all codes and their number of Items containing the respective code.现在我想获取所有代码及其包含相应代码的项目数。 Can I do that?我可以这样做吗?

Codes:代码:

 code|...
 ----|---
"A0A"|
"A0B"|
  ...|

Items:项目:

 ...|codestring
----|---------
    |"A0A C2B F1K"
    |"A0C D2S H3K"
    |...

Output:输出:

Codes:代码:

 code|...|noOfItems
 ----|---|---------
"A0A"|...|5
"A0B"|...|10
  ...|...|...

Assuming all the codes are distinct (or at least no code is a substring of another code), you can use the LIKE operator: (untested)假设所有代码都是不同的(或者至少没有代码是另一个代码的子字符串),您可以使用 LIKE 运算符:(未经测试)

SELECT codes.code, count(*)
FROM codes LEFT JOIN items ON items.codestring LIKE '%' + codes.code + '%'
GROUP BY codes.code;

You have a horrible data format and should fix it.你有一个可怕的数据格式,应该修复它。 The mapping to codes should have a separate row for each code.每个代码的映射到代码应该有一个单独的行。

If the codes are all three characters, then L Scott Johnson's answer is close enough.如果代码都是三个字符,那么 L Scott Johnson 的答案就足够接近了。 Otherwise, you should take the delimiter into consideration:否则,您应该考虑分隔符:

SELECT c.code, count(i.codestring)
FROM codes c LEFT JOIN
     items i
     ON ' ' || i.codestring || ' ' LIKE '% ' || c.code || ' %'
GROUP BY c.code;

Note other fixes to the code:注意代码的其他修复:

  • The concatenation operator is the standard ||连接运算符是标准的|| . .
  • The count() will return 0 if there are no matches.如果没有匹配项, count()将返回0

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

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