有没有更好的方法来创建case表达式而无需对其进行硬编码?
例如。
SELECT
CASE
WHEN PRICE BETWEEN 1 AND 10 THEN '$1~$10'
WHEN PRICE BETWEEN 11 AND 20 THEN '$11~$20'
WHEN PRICE BETWEEN 21 AND 30 THEN '$21~$30'
WHEN PRICE BETWEEN 31 AND 40 THEN '$31~$40'
WHEN PRICE BETWEEN 41 AND 50 THEN '$41~$50'
END AS PRICE_RANGE,
SUM(TRANSACTION_COUNT),
SUM(TRANSACTION_AMT)
FROM SALES
WHERE
CLR.DW_NET_PD_AMT BETWEEN 1 AND 10
OR CLR.DW_NET_PD_AMT BETWEEN 11 AND 20
OR CLR.DW_NET_PD_AMT BETWEEN 21 AND 30
OR CLR.DW_NET_PD_AMT BETWEEN 31 AND 40
OR CLR.DW_NET_PD_AMT BETWEEN 41 AND 50
GROUP BY 1;
我正在尝试根据上面显示的价格范围对价格进行分类。我需要将面额从$ 1- $ 500的钞票分类为10。
答案 0 :(得分:1)
您可以按以下方式重写查询:
您的输出将是:price-mod(price,10)
SELECT
price - mod(price, 10) as 'Min limit',
price + 10 - mod(price, 10) as 'Max limit' ... and so on
您可以使用模式将SELECT的输出转换为字符串。但是我专注于数学表达式以减少您的代码行。
因此,您可以通过这种方式删除CASE
答案 1 :(得分:0)
我不会生成从$ 1到$ 500的系列
但是我正在运行时创建一个。
假设您正在使用SQL SERVER
SELECT '$'+CONVERT(VARCHAR(100),PRICE/10*10+1)+'~$'+CONVERT(VARCHAR(100),(PRICE/10+1)*10)
答案 2 :(得分:0)
尝试一下。
SELECT '$' + CAST((@price / 10) * 10 + 1 AS varchar) + '~$' + CAST((@price / 10) * 10 + 10 AS varchar) AS PRICE_RANGE ,SUM(TRANSACTION_AMT) FROM SALES WHERE CLR.DW_NET_PD_AMT BETWEEN 1 AND 10 OR CLR.DW_NET_PD_AMT BETWEEN 11 AND 20 OR CLR.DW_NET_PD_AMT BETWEEN 21 AND 30 OR CLR.DW_NET_PD_AMT BETWEEN 31 AND 40 OR CLR.DW_NET_PD_AMT BETWEEN 41 AND 50 GROUP BY 1;