I have 2 tables, TableA and TableB
IdA | Date | Description
--- | ---------- | -----------
1 | 2017-01-01 | Sometext1
2 | 2017-01-01 | Sometext2
3 | 2017-01-02 | Sometext3
4 | 2017-01-03 | Sometext4
IdB | IdA | Type
--- | --- | ----
1 | 1 | A
2 | 1 | A
3 | 2 | A
4 | 2 | A
5 | 2 | B
6 | 3 | B
7 | 4 | A
Count(IdA) | Type
---------- | ----
3 | A
I have tried to code using INNER or LEFT JOIN like
SELECT COUNT(tablea.IdA), tableb.Type
FROM tablea INNER JOIN tableb
ON tablea.IdA=tableb.IdA
WHERE tableb.Type='A'
But it always get me like this
Count(IdA) | Type
---------- | ----
5 | A
I just want to count TableA row with WHERE clause from TableB. Is it possible to do something like that?
You probably want COUNT(DISTINCT col)
.
Try this:
SELECT
COUNT(DISTINCT a.IdA), b.Type
FROM
tablea a
INNER JOIN
tableb b ON a.IdA = b.IdA
WHERE
b.Type = 'A'
GROUP BY b.type
Yes, you need distinct column ids (but here's an answer using alias)
SELECT COUNT(distinct A.IdA), B.Type
FROM tablea A
INNER JOIN tableb B ON (A.IdA = B.IdA)
WHERE B.Type = 'A'
And you don't even need to put an ON clause if you join by the same column name so, making the sql even shorter.
SELECT COUNT(distinct A.IdA), B.Type
FROM tablea A
INNER JOIN tableb B
WHERE B.Type = 'A'
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.