[英]SQL count using multiple tables
Table 1: mappingtable (this contains the tags mapping with sentence) 表1:mappingtable(其中包含带有句子的标签映射)
id tag_id sentence_id
1 10 30
2 11 40
Table 2 reports 表2报告
sentence_id DATE property (sentences may repeat)
30 timestamp1 property1
30 timestamp2 property2
40 timestamp3 property1
I am trying to get the tag ids and count of tags grouped by time. 我正在尝试获取按时间分组的标签ID和标签计数。
I tried this query 我试过这个查询
SELECT DISTINCT(tag_id),COUNT(tag_id) AS cnt, MONTH(DATE) AS mnt
FROM mappingtable
INNER JOIN reports
ON mappingtable .sentence_id=reports.sentence_id AND reports.property= 'property1' GROUP BY tag_id,mnt ORDER BY cnt DESC;
However if the sentence repeats in the reports table (as is usually the case) the count of tags is coming wrong. 但是,如果该语句在报告表中重复(通常是这样),则标记计数就会出错。
Edit: 编辑:
Tried the query suggested below: 尝试了以下建议的查询:
SELECT M.tag_id, COUNT(M.tag_id) AS cnt, MONTH(R.DATE) AS mnt FROM mappingtable M INNER JOIN reports R ON M.sentence_id = R.sentence_id AND R.property = 'property1' GROUP BY M.tag_id, MONTH(R.DATE) ORDER BY COUNT(M.tag_id) DESC;
Even this query is giving additional counts because of repeating sentence ids. 甚至由于重复的句子ID,此查询也提供了额外的计数。
What I need is the unique sentences for property property1 grouped by month and then the tags counts of those sentences. 我需要的是按月分组的property1属性的唯一句子,然后是这些句子的标签计数。
tag_id cnt mnt
60865 145 11
60869 99 11
60994 74 11
61163 74 11
Something like this: 像这样:
SELECT
M.tag_id,
COUNT(M.tag_id) AS cnt,
MONTH(R.DATE) AS mnt
FROM mappingtable M
INNER JOIN reports R
ON M.sentence_id = R.sentence_id
AND R.property = 'property1'
GROUP BY M.tag_id,
MONTH(R.DATE)
ORDER BY COUNT(M.tag_id) DESC;
The inner join would take the records common to both tables. 内部联接将采用两个表共有的记录。 I believe thats why you are getting a wrong count of tags.
我相信这就是为什么您获得错误的标签计数的原因。 Even if a sentence has two properties, there would be just one occurrence in the join.
即使一个句子具有两个属性,联接中也只会出现一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.