[英]How do I get count of a row in SQL
I am a beginner regarding SQL queries so I hope that someone can help me with this. 我是有关SQL查询的初学者,所以希望有人可以帮助我。
I have a table that has 2 columns that are called MID and jachtID. 我有一个表,其中有2列称为MID和jachtID。 What I need is the count of how many of the same jachtIDS there are with different MIDS attached to them like this:
我需要的是计数多少个相同jachtIDS并附有不同的MIDS,如下所示:
MID jachtID
89 10
95 10
83 11
The result should look something like this: 结果应如下所示:
MID jachtID count
89 10 2
95 10 2
83 11 1
And I need this for all of the rows I have tried using 我尝试使用的所有行都需要这个
SELECT count(DISTINCT jachtID) FROM table
But this just gives me 1 big number and not the result that I need. 但这只是给我一个大数字,而不是我需要的结果。
Any help would be appreciated. 任何帮助,将不胜感激。
You can try the following query: 您可以尝试以下查询:
SELECT
T.MID,
T.jachtID,
jT.total
FROM table T INNER JOIN
(
SELECT
jachtID,
COUNT(*) total
FROM table
GROUP BY jachtID
)AS jT
ON T.jachtID = jT.jachtID
First get count
of each jachtID
by the following query: 首先通过以下查询获取每个
jachtID
的count
:
SELECT
jachtID,
COUNT(*) total
FROM table
GROUP BY jachtID
Then make an INNER JOIN
between the main table and the above query and get the corresponding jatchtID
count thereby. 然后在主表和上面的查询之间进行
INNER JOIN
,从而获得相应的jatchtID
计数。
You might be able to do this with some GROUP BY
magic, but I'm not sure, since you want all the rows. 您也许可以使用
GROUP BY
魔术来做到这一点,但是我不确定,因为您需要所有行。 Using a sub query will work, though. 但是,可以使用子查询。
SELECT
a.MID,
a.jachtID,
(SELECT count(b.jachtID) FROM table AS b WHERE b.jachtID= a.jachtID) AS `count`
FROM table AS a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.