为什么我的计数返回语法错误?

时间:2016-03-13 21:18:36

标签: sql sql-server

这是我的代码:

ALTER PROCEDURE [db_owner].[get_checkin_likes]
@likes integer
AS
Select count(*) 
from
(
  select checkin_id as Checkin, users_id as 'Liked by'
  from checkin_likes
  where @likes = checkin_id
)

当我执行此命令时,我期待两件事:

  1. 我希望得到所有喜欢我选择的特定签到的用户的列表
  2. 我希望能够计算出特定支票的用户数量
  3. 但是,当我尝试运行该命令时,它返回:

    Msg 102, Level 15, State 1, Procedure get_checkin_likes, Line 9
    Incorrect syntax near ')'.
    

    关于如何解决这个问题或者为什么会发生这种情况的任何建议?

1 个答案:

答案 0 :(得分:4)

您需要命名您的子查询;尝试在最后的括号后面放一些东西:

ALTER PROCEDURE [db_owner].[get_checkin_likes]
@likes integer
AS
Select count(*) 
from
(
  select checkin_id as Checkin, users_id as 'Liked by'
  from checkin_likes
  where @likes = checkin_id
) a

我可能应该提一下,当您运行此查询时,您只会获得倒计时。我不确定你的用例在这里,但是你可以做一个OVER并在最后用一个计数返回所有内容

编辑:

我个人会这样做并将其全部记录在一个记录集中:

ALTER PROCEDURE [db_owner].[get_checkin_likes]
@likes integer
AS

  select checkin_id as Checkin
    , users_id as 'Liked by'
    , COUNT(checkin_id) OVER () AS total_rows, 
  from checkin_likes
  where @likes = checkin_id