这个数据浏览器SQL查询有什么问题?

5

我正在尝试在Stack* Data Explorer上编写一个关于“我输入了多少字”的查询,涉及到IT技术相关内容。修改现有的查询已经让我进展了一部分:

-- How much did I type?

DECLARE @UserId int = ##UserId##

  select sum(len(Body)) AS 'Posts' from posts where owneruserid = @UserId,
  select sum(len(Text)) AS 'Comments' from comments where userid = @UserId,
  (select sum(len(Body)) from posts where owneruserid = @UserId +
  select sum(len(Text)) from comments where userid = @UserId) AS 'Total'

我希望能够得到一个包含三列和一行的表格,就像这样:
Posts    Comments    Total
1234     5678        6912

但是有一些语法问题,导致我出现以下错误:

错误:附近的逗号语法不正确。 附近的逗号语法不正确。选择关键字附近的语法不正确。 附近的括号语法不正确。

这个应该怎么写才是正确的语法?


这个问题涉及到http://odata.stackexchange.com/stackoverflow/query/new。随机的SQL查询并没有帮助解决问题。 - Aaron Butacov
@Aaron Harun:大家都做错了什么?是数据探索器只支持有效SQL查询的子集吗? - Lazer
基本上是这样的。他们需要使用TSQL,但有些人没有。在大多数“错误”的示例中,存在语法错误和其他使用了不同字段名称的情况。 耸肩 这种事情经常发生。 - Aaron Butacov
4个回答

3

以下是有效的查询:

DECLARE @UserId int;
set @UserID = 4;  

Select *, (Posts+Comments) as Total
FROM
  (select sum(len(Body)) AS Posts    FROM posts    where owneruserid = @UserId ) p,
  (select sum(len(Text)) AS Comments FROM comments where userid      = @UserId ) c

1

我会这样做...

declare @ownerId int
set @ownerId = 1

declare @Posts bigint
declare @Comments bigint

select
@Posts = sum(len(Body))
from Posts where owneruserid = @ownerId

select
@Comments = sum(len(Text))
from Comments where userid = @ownerId

select @Posts as 'Posts', @Comments as 'Comments', @Posts + @Comments as 'Total'

最初,我忘记在“sum”语句之前清除选择语句。现在应该没问题了。 - dhillis
@Aaron Harun,感谢您指引我使用数据浏览器。当我第一次查看问题时,我完全忽略了它。最终,我在我的SQL服务器上创建了自己的表格(尽管表格/列名不同)。现在我知道了。 - dhillis

1

你的问题是将3个语句连接成了1个语句 - 只需将其合并为一个语句:

例如:
select sum(len(Body)) AS 'Posts', sum(len(Text)) AS 'Comments' , sum(len(Body)) + sum(len(Text)) AS Total
from posts t1 inner join comments t2 on t1.owneruserid = t2.userid 
where t1.owneruserid = @UserId

希望我打对了...


0
-- 我打了多少字?
/* 如果这是来自您的应用程序的参数,则无需在此处声明*/ DECLARE @UserId int; set @UserID = 4;
SELECT *, (Posts+Comments) AS Total FROM (SELECT SUM(LEN(Body)) AS Posts FROM posts WHERE owneruserid = @UserId ) p, (SELECT SUM(LEN(Text)) AS Comments FROM comments WHERE userid = @UserId ) c

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接