![](/img/trans.png)
[英]MySQL. How can I COUNT() but insert different value on the different column?
[英]MySql. How can i get count from 2 tables
我有2個表TableA和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
我試圖使用INNER或LEFT JOIN進行編碼,例如
SELECT COUNT(tablea.IdA), tableb.Type
FROM tablea INNER JOIN tableb
ON tablea.IdA=tableb.IdA
WHERE tableb.Type='A'
但這總是讓我這樣
Count(IdA) | Type
---------- | ----
5 | A
我只想使用來自TableB的WHERE子句來計數TableA行。 可以做這樣的事情嗎?
您可能需要COUNT(DISTINCT col)
。
嘗試這個:
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
是的,您需要不同的列ID(但這是使用別名的答案)
SELECT COUNT(distinct A.IdA), B.Type
FROM tablea A
INNER JOIN tableb B ON (A.IdA = B.IdA)
WHERE B.Type = 'A'
如果您使用相同的列名進行連接,甚至不需要放置ON子句,從而使sql更短。
SELECT COUNT(distinct A.IdA), B.Type
FROM tablea A
INNER JOIN tableb B
WHERE B.Type = 'A'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.