Skip to content
Advertisement

Subquery to get derived value

I have the below table T in MySQL, with columns A and B.

enter image description here

I want to query this table to get a value ‘C’, that has the count of the number of times the value in Column ‘A’ appears in Column ‘B’. For example, 1 appears 2 times in Column B, so the first row of column C should be 2. I don’t want to iterate over the table, so I want to get this using subqueries. The desired output is given below.

enter image description here

I tried using the below query

But I got 0 for all rows in column C. Please help me identify the mistake.

Advertisement

Answer

Use a correlated subquery:

Or:

Or with a self LEFT join and aggregation:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement