Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 count records in group by query

Author  Topic 

ddiabetes
Starting Member

1 Post

Posted - 2014-01-27 : 18:56:30
I have an online shopping cart, where one customer may make a dozen separate orders for shipment to different addresses, each day.

I want to create a temp table where the items are grouped by customer and then, sequentially number each line related to that customer. I can do it in vbscript, increasing the count by 1 for each iteration while the customer ID (email) is the same. When the customer ID changes, the count goes back to 1.
Here is the code snippet:
>> Code begins:

count=1

rscustomer = "SELECT DT_CUSTINFO.email, And a bunch of other stuff with a GROUP BY clause in there, but it's not important for this question"


newrep= rscustomer("email")

do until rscustomer.eof


If rscustomer("EMAIL")<> newrep then


newrep= rscustomer("EMAIL")

COUNT=1


end if


if rscustomer.eof = false then

rscustomer.movenext


count = count + 1

end if

rscustomer.movenext

LOOP
>>> End of code snippet.
I am lost when trying to create a stored procedure in MS SQL 2005.

Any help would be appreciated.
Thanks!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2014-01-27 : 22:33:06
[code]SELECT DT_CUSTINFO.email, CNT = ROW_NUMBER() OVER (ORDER BY DT_CUSTINFO.email)
FROM yourtable
GROUP BY DT_CUSTINFO.email[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -