Reputation: 315
I am a beginner regarding SQL queries so I hope that someone can help me with this.
I have a table that has 2 columns that are called MID and jachtID. What I need is the count of how many of the same jachtIDS there are with different MIDS attached to them like this:
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.
Upvotes: 2
Views: 74
Reputation: 13519
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:
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.
Upvotes: 4
Reputation: 13635
You might be able to do this with some GROUP BY
magic, but I'm not sure, since you want all the rows. 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
Upvotes: 2