I am trying to use a CAST() in an SQL statement but it doesn’t allow me to see the CAST(myDateTime, Date) as myLoginShortDate in the group by? I only know the basics of SQL and I am trying to learn more.
May data looks like this:
CustomerID int, null
Email varchar(60)
DateEntered DateTime
I am trying to get the a grouping by the date part of the datetime and grouped on the Email
My stored procedure select part looks like this:
select cll.Email,CAST(cll.DateEntered as Date) as LoginDate,
COUNT(cll.email) as FailedCount
from [GC].[dbo].[CustomerLoginLog] as cll
where [CustomerId] is null
group by LoginDate, cll.Email
order by FailedCount desc`
It is returning "Invalid column name ‘LoginDate’"
I want to be able to see:
Email, LoginDate, FailedCount
xyz@test.com, 11/01/12, 21
abc@test2.com, 11/01/12, 17
xyz@test.com, 10/30/12, 15
and so on. I am sure this is just a beginners mistake. I have this post all messed up but I hope somebody understands it. The select format looks better on my computer.
The
GROUP BYstatement is evaluated before theSELECTstatement, so SQL server doesn’t know about the alias you gave the expression in theSELECTstatement. To remedy this, you simply have to repeat the expression in theGROUP BY:Or wrap the simple part of your query with a CTE, and do the grouping on the CTE results:
Alternatively you could include the content of the CTE as in a nested SELECT statement as Mahmoud pointed out.