简体   繁体   中英

Count the number of entries in the table

I have a table allData

id     name       
1      meat
2      chicken
3      fish
4      chicken
5      fish
6      chicken

and table relevantData

id        name
1         meat
2         fish

I want to count the total number of occurrence per name in allData , but only for names which appear in relevantData . Ie The result I want to get :

id       name     count
1        meat     1
2        fish     2

I thought about the query:

Select count(*) from allData group by name

Not sure how I correlate with relevantData . Any thoughts?

Change the point of view, you are interested in relevantData , that's the base of your query. You can use a correlated subquery, no need to use join or group-by:

SELECT rd.name, 
       (SELECT COUNT(*) FROM allData ad WHERE rd.name = ad.name) AS Count
FROM relevantData rd

Demo

您可以尝试以下方法。

SELECT COUNT(*) FROM allData WHERE name in (SELECT name from relevantData) GROUP BY name

Simply join them together:

SELECT  a.id, a.name, COUNT(*) AS CntCol
FROM    allData a
        INNER JOIN relevantData r ON a.name = r.name
GROUP BY a.id, a.name

Try this:

SELECT a.name, Count(1) AS TotalCount
FROM allData a
WHERE EXISTS(SELECT TOP 1 1 FROM relevantData WHERE a.name = name)
GROUP BY a.name

Just group it by id and check if it contains in relevantData

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