0

I want to select some rows and want to return those rows plus an additional column that display the count of selected rows. I am using a derived version of sql that doesnot allow me use OVER() AS function as discussed here . I want something like for each element in selected column ,I want a count of it in entire table Like

For Initial column like this :

Fruits
Apple
Mango
Fruits
Banan

Final returned values :

Fruits NewColumnwithCount 
Apple   2
Mango   1
Apple   2
Banana  1

Like in selected colum called Fruits, Apple appear 2 times, banana 1 times and Mango 1 time (in the entire selected column called fruits)

danish sodhi
  • 1,793
  • 4
  • 21
  • 31

2 Answers2

2

use a GROUP BY as:

SELECT COUNT(FruitID), FruitName FROM Fruits GROUP BY FruitName;

UDPATE

SELECT FruitName, (select count(fs.id) FROM Fruits fs where fs.id = f.id GROUP BY fs.FruitName) as 'count' FROM Fruits f;

The subquery will return how many times the selected fruit is present

Josue Martinez
  • 436
  • 5
  • 14
1

You are looking for window functions:

select fruit, count(*) over (partition by fruit) as NewColumnwithCount
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786