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)

3
  • 2
    Please add the tag for the DBMS do you use Commented Jul 2, 2017 at 15:10
  • I can't understand the connection between your sample data and your desired results. Commented Jul 2, 2017 at 15:11
  • @ZoharPeled , Like in selected colum called Fruits, Apple appear 2 times, banana 1 times and Mango 1 time (in the entire selected column called fruits) Commented Jul 2, 2017 at 15:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

But this will group all Apples together , no ? I want each time apple appears as it is, with additional information of the count
ok I get it now...then use a sub-query for the count. Check the updated answer
1

You are looking for window functions:

select fruit, count(*) over (partition by fruit) as NewColumnwithCount
from t;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.