简体   繁体   English

用聚合函数计算SQL

[英]Counting with aggregate functions SQL

I have a database with a table that holds all codes and a second table that holds codes that apply to data that can't be turned into primary key(hence a huge problem with it). 我有一个数据库,该数据库的一个表包含所有代码,第二个表包含适用于无法转换为主键的数据的代码(因此存在很大的问题)。 Sometimes the codes are held in such a way "E1/D2/E3" in the comments section so multiple codes can appear in one comment 有时,在注释部分中以“ E1 / D2 / E3”的方式保存代码,因此一个注释中可以出现多个代码

What I need is to get a list of codes of certain level and then use it with a LIKE statement to find a count of how many times each code exists in this particular database for example. 我需要的是获取特定级别的代码列表,然后将其与LIKE语句一起使用,以查找每个代码在此特定数据库中存在多少次的计数。

Count how many times each code exists in the codes column of the comments table. 计算注释表的“代码”列中每个代码存在多少次。 I've figured to get a list of Codes of this level and then I'm stuck with it. 我已经想出了这个级别的代码列表,然后我坚持了下来。 Please help 请帮忙

Code Table: 代码表:

+----+-----------+-----+
|Code|Description|Level|
+----+-----------+-----+
|A1  |desc       |1    |
+----+-----------+-----+
|A2  |desc       |1    |
+----+-----------+-----+
|A3  |desc       |1    |
+----+-----------+-----+
|A4  |desc       |1    |
+----+-----------+-----+
|A1.1|desc       |2    |
+----+-----------+-----+
|A2.1|desc       |2    |
+----+-----------+-----+
|A3.1|desc       |2    |
+----+-----------+-----+
|A4.1|desc       |2    |
+----+-----------+-----+

Comments Table: 评论表:

+-------------+----------+-------------+
|Comment      |Codes     |Location     |
+-------------+----------+-------------+
|Hello there  |A1/A1.1/A2|Somewhere    |
+-------------+----------+-------------+
|How are you  |A4/A7/B1.1|Long time ago|
+-------------+----------+-------------+
|My name is...|B1/B2/B3  |Somewhere    |
+-------------+----------+-------------+

Now what I need is to count the amount of times each code from level 1 occured in the comments section for each tuple. 现在,我需要计算每个元组的注释部分中级别1的每个代码出现的次数。

If you mean how often each code appears in the codes column of the comments table: 如果您是指每个代码在注释表的“ 代码”列中出现的频率:

select co.code, count(*)
from comments c join
     codes co
     on find_in_set(co.code, replace(c.codes, '/', ',')) > 0 and
        co.level = 1
group by co.code;

EDIT: 编辑:

You can also express this using like : 你也可以使用这个使用like

select co.code, count(*)
from comments c join
     codes co
     on concat('/', c.codes, '/') like concat('%/', co.code, '/%')
        co.level = 1
group by co.code;

Note that appending of delimiters at the beginning and end to ensure full matches. 请注意,在开头和结尾处添加定界符以确保完全匹配。

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

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