查询计数的SQL Server计数值

时间:2018-03-15 17:31:41

标签: sql sql-server

我的查询如下:

linear-gradient(to left, currentcolor, currentcolor);

但是,我的查询无法很好地执行,我收到此错误:

  

Msg 102,Level 15,State 1,Server WIN-ILO9GLLB9J0,Line 33
  ')'

附近的语法不正确

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

在SQL Server或MySQL中需要子查询的别名:

SELECT COUNT(*)
FROM (SELECT h2.hacker_id, count(c2.challenge_id) as co
      FROM hackers h2 INNER JOIN 
           challenges c2
           ON h2.hacker_id = c2.hacker_id
      GROUP BY h2.hacker_id
      HAVING count(c2.challenge_id) = 1
     ) x;

假设您的hacker_id都已明确定义,则不需要JOIN

SELECT COUNT(*)
FROM (SELECT c2.hacker_id, count(c2.challenge_id) as co
      FROM challenges c2
      GROUP BY c2.hacker_id
      HAVING count(c2.challenge_id) = 1
     ) x;

如果您在challenges中有唯一ID,则还可以将其标记为:

select count(*)
from challenges c
where not exists (select 1
                  from challenges c2
                  where c2.hacker_id = c.hacker_id and c2.challenge_id <> c.challenge_id
                 );

使用challenges(hacker_id, challenge_id)上的索引,这应该具有最佳性能(再次,无论数据库如何)。

答案 1 :(得分:1)

您需要FROM()表的表名,例如在结束后添加一个简单的T)

SELECT COUNT(*)
FROM (
    SELECT h2.hacker_id, count(c2.challenge_id) as co
    FROM hackers h2 INNER JOIN challenges c2 ON h2.hacker_id = c2.hacker_id
    GROUP BY h2.hacker_id
    HAVING count(c2.challenge_id) = 1
) T