Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SP Counting Advanced 1

Status
Not open for further replies.

free47

Programmer
Jun 9, 2008
10
US
I am trying to make a stored proc that will count the number of times each company comes up but keep the number of times the company comes up. Here is an example of my data set.

Company | ID | Topic | Details
1 25 RD TBD
1 25 RD TBD
2 26 RD TBD
3 27 RD TBD
3 27 RD TBD
3 27 RD TBD

I want the final result of the query to be with it ordered by the count :

Company | ID | Topic | Details | Count
3 27 RD TBD 3
3 27 RD TBD 3
3 27 RD TBD 3
1 25 RD TBD 2
1 25 RD TBD 2
2 26 RD TBD 1


Is this possible in SQL?

Thanks in advance! :)
 
yes. YOu'll need to create a derived table that stores just the recordid and the count. Then join it to your regular table and you should be fine.

"NOTHING is more important in a database than integrity." ESquared
 
I am looking at this example query and dont see how it would fit into my query.
Code:
SELECT LastName, FirstName
	FROM
		(SELECT * FROM Employee
		 WHERE State = "NY") AS EmployeeDerivedTable
	WHERE LastName = "Smith"
	ORDER BY FirstName

This is my query before i put in the derived table

Code:
SELECT     Incident.Division, Incident.id, Topic.name AS topic, LineOfBusiness.name AS lob, Incident.details

FROM         Incident INNER JOIN
                      Topic ON Incident.topic = Topic.id INNER JOIN
                      LineOfBusiness ON Incident.lob = LineOfBusiness.id
WHERE     (Incident.dateCreated BETWEEN @StartDate AND @EndDate) AND (Incident.customerEscalated = 1)
 
Code:
SELECT YourTable.Company,
       YourTable.ID,
       YourTable.Topic,
       YourTable.Details,
       Tbl1.Cnt
FROM YourTable
INNER JOIN (SELECT Id, COUNT(*) AS Cnt
                   FROM YourTable
            GROUP BY Id) Tbl1
      ON YourTable.id = Tbl1.Id
ORDER By Tbl1.Cnt, Id

Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
Borislav, thanks again, you really are the SQL expert!!! Thanks for helping others learn! :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top