简体   繁体   中英

SQL count using multiple tables

Table 1: mappingtable (this contains the tags mapping with sentence)

id  tag_id     sentence_id

1           10         30

2           11         40

Table 2 reports

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.

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:

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.

What I need is the unique sentences for property property1 grouped by month and then the tags counts of those sentences.

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.

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