0

I always seem to trip myself up during these types of SQL Statements. Here is what I'm attempting to accomplish.

My Example Table

Name    Date    Type
Bob     9/28/11 1
Bob     9/27/11 1
Bob     9/28/11 2
Debra   9/28/11 1

I'm trying to write a SQL Statement that would give me all the names, their total count occured, and then a Date Filter. I'll write a rought statement with completely wrong syntax, but I think it'll convey what I'm attempting to do...I think.

SELECT Name, Count(*) As Total
FROM Table
GROUP BY Name, Total
WHERE Date = Today (I'm aware you can't do a WHERE in a GROUP BY) AND Type = 1

Essentially, I would like to get back a set of data that would show the Name, how many instances of Type 1 for today.

I don't think I'm searching for the proper question to actually be able to effectively research this on my own as well, probably because I'm wording it improperly.

Any help would be appreciated!

1
  • @AbeMiessler It would be a simple resultset of the name with the total count for that name, and then to the next name, etc. I do believe it was a simple syntax error, and I just didn't see it. The folks below explained that the WHERE comes before the GROUP BY and for some jacked up reason....it just didn't click for me. I've been looking at code all day...fatigue. Commented Sep 28, 2011 at 21:00

3 Answers 3

3

Your WHERE was in the wrong place:

SELECT Name, Count(*) As Total
FROM Table
WHERE Date = Today AND Type = 1
GROUP BY Name
Sign up to request clarification or add additional context in comments.

Comments

2

You just need to move your WHERE after your FROM.

SELECT Name, Count(*) As Total
FROM Table
WHERE [Date] = CAST(getdate() as Date) -- or 'Jan 1 1990'
AND [Type] = 1
GROUP BY Name 

1 Comment

+1 possibly need to cast the Date field also (if it is a DateTime)
2

WHERE comes before GROUP

SELECT Name, Count(*) As Total
FROM Table
WHERE Date >= @Today --assuming your date passed in has no time
AND Date < DATEADD(d,1,@Today) 
AND Type = 1
GROUP BY Name, Total

example you can run

SELECT LEFT(name,1) FROM sysobjects
WHERE name < 'p'
GROUP BY LEFT(name,1) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.