Home > other >  Case statement in group by clause
Case statement in group by clause

Time:11-09

My current query works however, I can not seem to get another column name to explain what the data is.

Query:

SELECT 
    SUM(item_subtotal) AS rev
FROM 
    [ADAS].[dbo].[ADAS_ORDERS] x
LEFT JOIN 
    ADAS.dbo.ADAS_SUBSCRIPTIONS y ON x.SUBSCRIPTION_KEY = y.SUBSCRIPTION_KEY
                                  AND x.CUSTOMER_ID = y.customer_id
                                  AND x.ITEM_NUM = y.ITEM_NUM
WHERE
    x.ORDER_DATE BETWEEN '10-01-2021' AND '10-31-2021'
    AND x.ORDER_STATUS = 'success' 
    AND x.IMPULSE_FLG = 'n'
GROUP BY
    CASE 
        WHEN y.OFFER_ID IS NULL 
            THEN 'Null' 
        WHEN y.OFFER_ID IN ('1882', '1883', '4554', '4576') 
            THEN 'in-store' 
        ELSE 'web'  
    END
ORDER BY 
    1

Result

"Blank"   rev
1         221243
2
3

How do I get the other column to have a name?

CodePudding user response:

You may try including the case expression in the group by in your select/projection also eg

SELECT 
sum(item_subtotal)as rev,

  case when y.OFFER_ID is null then 'Null' 
  when y.OFFER_ID in('1882','1883','4554','4576') then 'in-store' else 'web' end as offer_location

  FROM [ADAS].[dbo].[ADAS_ORDERS] x
  left join ADAS.dbo.ADAS_SUBSCRIPTIONS y on x.SUBSCRIPTION_KEY = y.SUBSCRIPTION_KEY
  and x.CUSTOMER_ID = y.customer_id
  and x.ITEM_NUM = y.ITEM_NUM
  where x.ORDER_DATE between '10-01-2021' and '10-31-2021'
  and x.ORDER_STATUS = 'success' 
  and x.IMPULSE_FLG = 'n'
  group by  case when y.OFFER_ID is null then 'Null' 
  when y.OFFER_ID in('1882','1883','4554','4576') then 'in-store' else 'web' end
  order by 1
  • Related