13
Views
4
Comments
Solved
Having is not working with group by
Question

i have having select to find the number of weeks 

SELECTDATEPART(wk, oRESULT.[CREATED_AT]) Title,COUNT(oRESULT.[Id]) Value

but when i am using  having its not working ! 

and all have condition is not affect the querry

Solution

Hi Omar

I think you are mistaking HAVING for the WHERE clause

HAVING filters rows within each of the groups defined by GROUP BY.

First the WHERE clause filters all the rows where you want to do the GROUP BY on. Then with having you can filter those rows created by the GROUP BY

Example:

SELECT   orders.customerid , SUM (price)

FROM    orders

WHERE  orders.status > 50

GROUP BY orders.customerid

HAVING SUM(price) > 1000


In this query the price is SUMMED per customerid for all orders with status > 50.

Only when the summed price > 1000 it is shown in the list.


Does this make any sense to you?

Best regards


this when i use group by 

dummy sample 



SELECT 


DATEPART(wk, {x}.[CREATED_AT]) Title,

COUNT({x}.[Id]) Value


FROM

{x}



GROUP

BY

DATEPART(wk, {x}.[CREATED_AT])  ,

{x}.[Id] ,

{x}.[TITLE] ,

{x}.[CATEGORY_ID],



HAVING


({x}.[TITLE] LIKE '%'+@REQUEST_TITLE+'%' or @REQUEST_TITLE = '')

AND 

({x}.[WF_NO] LIKE '%'+@WF_NO+'%' or @WF_NO = '')


Hi Omar abdElhaid,

Use where clause instead of having clause. It will help you. Like this,

SELECT 

DATEPART(wk, {x}.[CREATED_AT]) Title,

COUNT({x}.[Id]) Value

FROM {x}

WHERE 

({x}.[TITLE] LIKE '%'+@REQUEST_TITLE+'%' or @REQUEST_TITLE = '')

AND 

({x}.[WF_NO] LIKE '%'+@WF_NO+'%' or @WF_NO = '')

GROUP BY

DATEPART(wk, {x}.[CREATED_AT])  ,

{x}.[Id] ,

{x}.[TITLE] ,

{x}.[CATEGORY_ID],


Thanks, And regards,

Parveen

Solution

Hi Omar

I think you are mistaking HAVING for the WHERE clause

HAVING filters rows within each of the groups defined by GROUP BY.

First the WHERE clause filters all the rows where you want to do the GROUP BY on. Then with having you can filter those rows created by the GROUP BY

Example:

SELECT   orders.customerid , SUM (price)

FROM    orders

WHERE  orders.status > 50

GROUP BY orders.customerid

HAVING SUM(price) > 1000


In this query the price is SUMMED per customerid for all orders with status > 50.

Only when the summed price > 1000 it is shown in the list.


Does this make any sense to you?

Best regards


Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.