[英]Case statement in group by clause
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结果
How do I get the other column to have a name?我如何让另一列有一个名字?
You may try including the case expression in the group by in your select/projection also eg您也可以尝试在选择/投影中包含组中的 case 表达式,例如
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.