Click here to Skip to main content
14,869,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All
Please help me in clarifying about the Group By Clause a little bit more.I tried to use an additional (User defined col) in my Group By clause, which is not present as original column in the Group by, However its ending up with error again:(!!

What I have tried:

The Query:
select CustName,Count(CustName),PurchaseDate,DATENAME(dw,PurchaseDate) as Day from [CustmrSrc] where Day = 'Monday' and Day ='Tuesday' and  Day='Wednesday' and Day='Thursday'and Day='Friday' Group By CustName, PurchaseDate ,Day


Error:-
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.


Regards
Posted
Updated 21-Aug-16 22:30pm

You can include a user-defined column in your WHERE and GROUP BY clauses, but you have to use the full declaration instead of the name.
Applied to your example, this would give:
SQL
SELECT
  CustName
 ,Count(CustName)
 ,PurchaseDate
 ,DATENAME(dw,PurchaseDate) as Day
FROM
 [CustmrSrc]
WHERE
    DATENAME(dw,PurchaseDate) = 'Monday'
 OR DATENAME(dw,PurchaseDate) = 'Tuesday'
 OR DATENAME(dw,PurchaseDate) = 'Wednesday'
 OR DATENAME(dw,PurchaseDate) = 'Thursday'
 OR DATENAME(dw,PurchaseDate) = 'Friday'
GROUP BY
  CustName
 ,PurchaseDate

A few notes:
- Here you need OR conditions, not AND. A given date cannot be a monday and a tuesday at the same time.
- Since you already included the PurchaseDate column in the GROUP BY clause, you do not need to also include the day name (the PurchaseDate already defines the week-day).

Kindly.
   
Comments
mousau 22-Aug-16 4:37am
   
Hi Phil
Thanks a lot for the response and providing the clarity.
Gotta a question now! Tried the same query using "IN" clause, but I do need to fetch the details of the those customers who are purchasing on any of the five days regularly, but I am struggling here:(

Thank You
Regards
You pass the expression you want to group by rather than the alias
Like below
SQL
select CustName,Count(CustName),PurchaseDate,DATENAME(dw,PurchaseDate) as Day from [CustmrSrc] A

where DATENAME(dw,PurchaseDate) = 'Monday' or DATENAME(dw,PurchaseDate) ='Tuesday' or  DATENAME(dw,PurchaseDate)='Wednesday' or DATENAME(dw,PurchaseDate)='Thursday'or DATENAME(dw,PurchaseDate)='Friday'

Group By CustName, PurchaseDate ,DATENAME(dw,PurchaseDate)
   
Comments
mousau 22-Aug-16 4:47am
   
Hi Sumon
Thanks a lot for the response.
Regards

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900