开发者

Whats wrong with this Data Explorer SQL query?

开发者 https://www.devze.com 2023-01-05 04:08 出处:网络
I am trying to write a How much 开发者_JS百科did I type? query on Stack* Data Explorer. Modifying an existing query got me this far:

I am trying to write a How much 开发者_JS百科did I type? query on Stack* Data Explorer.

Modifying an existing query got me this far:

-- 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'

I am expecting three columns and one row, something like this:

Posts    Comments    Total
1234     5678        6912

But there is some syntax problem, due to which I get:

Error: Incorrect syntax near ','. Incorrect syntax near ','. Incorrect syntax near the keyword 'select'. Incorrect syntax near ')'.

What is the correct syntax for this?


Here is a working query:

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


I would do it this way...

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'


Hi your problem is that you have 3 Statements concatenated to 1 Statement - just make one Statement out of if: like

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

Hope I typed correct ...


-- How much did I type?

/* If this is to be a parameter from your app, you don't need to declare it here*/
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
0

精彩评论

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