简体   繁体   中英

SQL count number of results for a specific record

I have 2 tables which are linked via INNER JOIN. These are my tables:

T1
ID    name  Account
1     name1  123
1     name1  143

T2
AccountNum    ID
222           1
111           1

I would like to add the total number of ByID for a specific name, my output should be

ID    name  Account  NumOfByAcc
 1    name1   123    2

In above table what happening is ID 1 has two account numbers(T2) how would I count the total number of account numbers for a specific ID using INNER JOIN between two tables. This is my query but I am not sure how would I complete my second select statements:

SELECT        Table1.ID, Table1.NAme, Table2.Account AS Expr1, 

                     SELECT count() AS NumOfByAcc//2nd select statement 
FROM            Table2 INNER JOIN
                     Table1 ON Table2.ID= Table1.ID

I am not sure how would I complete my second select statements:

Like this:

SELECT
   t1.ID
,  t1.NAme
,  t2.Account AS Expr1
,  (SELECT count(*) FROM Table1 tt WHERE tt.ID=t2.ID) AS NumOfByAcc 
FROM  Table2 t2
INNER JOIN Table1 t1 ON t2.ID= t1.ID

Note the use of aliases t1 , t2 , and tt . When the same table needs to participate in a single query more than once, aliases provide a way to reference that table in your expressions to filter and/or join the records as needed.

select *, (select count(*) from T2 where T2.Id = T1.Id) as NumOfByAcc
from T

Try:

SELECT      T1.id,
            T1.name
            T1.account,
            V1.accountcount
FROM        T1
INNER JOIN
(
    SELECT      T2.id,
                COUNT(*) accountcount
    FROM        T2
    GROUP BY    T2.id
) V1
ON          T1.id = V1.id

It's the GROUP BY clause that does the heavy lifting.

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