简体   繁体   中英

SQL: count occurrences for each row

I have an SQL table called Codes with a primary column code of type String. I also have another table called Items with a column codestring also of type 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)

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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