Skip to content
Advertisement

Group by to include case statement inside SQL statement

I have a table which stores purchase info from sellers and table contains rating to every purchase out of 5 stars. I want to have output Group By sellers and Each sellers good(Above 3) and bad(Below 4) ratings count

PurchaseId  SellerId    PurchaseRating
1            ABC         2
2            ABC         5
3            DEF         1
4            XYZ         2
5            DEF         4
7            ABC         3

OUTPUT 
SellerId     TotalOrders   AvgRating    Above3*(4&5)  Below4*(1 to 3)
ABC           3             3.3        1              2
DEF           2             2.5        1              1
XYZ           1              2         0              1

For first 3 columns I am getting result using this

Select SellerId, Count(P.Id) TotalOrders, Avg(PurchaseRating) AvgRating, 
CASE WHEN P.PurchaseRating >= 4 THEN 1 ELSE 0 END AS Above3*(4&5)
 from 
  [dbo].[AmazonAbeOrdersPurchaseInfo] P 
   Where PurchaseRating is not null
  Group by P.SellerId
  order by TotalOrders desc

Unable to identify how to include case in group by clause.

Advertisement

Answer

You are trying to do conditional aggreation. The important thing is that you want the conditional expression inside the aggregate function:

select 
    sellerId,
    count(*) totalOrders,
    avg(purchaseRating) avgRating,
    sum(case when purchaseRating > 3 then 1 else 0 end) above3,
    sum(case when purchaseRating < 4 then 1 else 0 end) below4
from [dbo].[AmazonAbeOrdersPurchaseInfo]
where purchaseRating is not null
group by sellerId
order by totalOrders desc
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement