开发者

Assign value for each row

How to assign t-sql expression for each tables row? For example:

Foreach user in Users
{
user.Place = SELECT COUNT(*) AS [value]
FROM [Users] AS [t0]
WHERE (COALESCE([t0].[Votes],@p0)) > @p1;
}

where Users is ta开发者_如何学Cble. It's pseudo-code but I want to do that in t-sql stored procedure.


So you want all user records, and with each record, a count..

You can use a subquery - but what are @p0 and @p1? Check this

SELECT u.*, Place = (
    SELECT COUNT(*) AS [value]
    FROM [Users] AS [t0]
    WHERE COALESCE([t0].[Votes],0) > u.Votes)
FROM Users u

From SQL Server 2005+, you can use windowing functions

SELECT u.*, Place = Rank() over (order by u.Votes)
FROM Users u


Are you looking for something like

ROW_NUMBER (Transact-SQL), RANK (Transact-SQL) or DENSE_RANK (Transact-SQL)

Also have a look at this example


Is this what you mean:

UPDATE Users
SET Place = (
  SELECT COUNT(*)
  FROM Users
  WHERE COALESCE(Votes, @p0) > @p1
)

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜