Lazer
Lazer

Reputation: 94930

Whats wrong with this Data Explorer SQL query?

I am trying to write a How much 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?

Upvotes: 5

Views: 250

Answers (4)

Aaron Butacov
Aaron Butacov

Reputation: 34367

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

Upvotes: 3

Tobias Pirzer
Tobias Pirzer

Reputation: 1025

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

Upvotes: 1

dhillis
dhillis

Reputation: 106

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'

Upvotes: 1

jmoreno
jmoreno

Reputation: 13571

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

Upvotes: 0

Related Questions