views:

120

answers:

4

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?

+3  A: 

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
Aaron Harun
+1  A: 

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'
dhillis
Originally, I forgot to clear out the select statements before the "sum" statements. It should be good now.
dhillis
sorry, I'm tired and didn't notice the subselects...new version coming...
dhillis
Test the query here: http://odata.stackexchange.com/stackoverflow/query/new
Aaron Harun
@Aaron Harun, thanks for pointing me to data explorer. I totally overlooked that when I first viewed the question. I ended up creating my own tables on my sql server (albeit with different table/column names). Now I know.
dhillis
A: 
-- 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
jmoreno
You had an extra equals, other than that, it works.
Aaron Harun
+1  A: 

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

Tobias Pirzer