[英]Value format based on 1st Column value in select query in SQL server
I have table TableA as below我有如下表 TableA
Channel | Column1 | Column2 | Column3
---------------------------------------------
Channel1 % 10.20 10.30 15.50
Channel2 1000 10000 1000000
Channel3 % 5.10 8.50 12.45
Channel4 50000 3000 1500000
I want to develop select query to apply % sign next to value and K(thousand) and M(Millions) logic so that it return as below.我想开发 select 查询以在值和 K(千)和 M(百万)逻辑旁边应用 % 符号,使其返回如下。
Channel | Column1 | Column2 | Column3
---------------------------------------------
Channel1 % 10.20% 10.30% 15.50%
Channel2 1000 10K 1M
Channel3 % 5.10% 8.50% 12.45%
Channel4 50K 3000 1.5M
This is strange.这很奇怪。 But assuming the values are strings, you can use
case
expressions:但假设值是字符串,您可以使用
case
表达式:
(case when channel like '%$%' escape '$'
then concat(column1, '%')
when column1 >= 1000 and column1 < 1000000
then concat(left(column1, len(column1) - 3), 'K')
when column1 >= 1000000
then concat(left(column1, len(column1) - 6), 'M')
else column1
end) as column1
Just repeat this logic for all the columns.只需对所有列重复此逻辑即可。
I think this might be a bit simpler than Gordon's logic, but the same idea:我认为这可能比 Gordon 的逻辑更简单,但同样的想法:
CASE
WHEN RIGHT(channel, 1) = '%' THEN CONCAT(column1, '%')
WHEN column1 >= 1000000 THEN FORMAT(column1/1000000.0, '0.#M')
WHEN column1 >= 1000 THEN FORMAT(column1/1000.0, '0.#K')
ELSE column1
END as column1
You might need some specific formatting depending on the number of decimal places you want in your K and M;您可能需要一些特定的格式,具体取决于您想要的 K 和 M 中的小数位数; you could
CONCAT(CAST(column1/1000.0 AS FLOAT), 'K')
but it's a bit of a cheat way to reduce the number of trailing 0 on a number.你可以
CONCAT(CAST(column1/1000.0 AS FLOAT), 'K')
但这是一种减少数字尾随 0 数量的作弊方法。 If your SQLS supports FORMAT like FORMAT(column1/1000.0, '0.#K')
you should consider using it instead如果您的 SQLS 支持 FORMAT,例如
FORMAT(column1/1000.0, '0.#K')
您应该考虑使用它
You can use FORMAT function, but instead of hardcoding number, we can use like this.您可以使用 FORMAT function,但我们可以这样使用而不是硬编码数字。 Though this kind of conversion should not be done at SQL Server and presentation application should handle this
虽然这种转换不应该在 SQL 服务器和演示应用程序处理这个
SELECT
Channel1,
CASE
WHEN LEN(FLOOR(COL1)) <= 2 THEN CONCAT(COL1,'%')
WHEN (LEN(FLOOR(COL1)) >= 4 AND LEN(FLOOR(COL1)) <=5) THEN FORMAT(COL1,'0,K')
WHEN LEN(FLOOR(COL1)) >= 5 THEN CONCAT(COL1,'M')
END AS COL1,
CASE
WHEN LEN(FLOOR(COL2)) <= 2 THEN CONCAT(COL2,'%')
WHEN (LEN(FLOOR(COL2)) >= 4 AND LEN(FLOOR(COL2)) <=5) THEN FORMAT(FLOOR(COL2),'0,K')
WHEN LEN(FLOOR(COL2)) >= 5 THEN FORMAT(FLOOR(COL2),'M')
END AS COL2,
CASE
WHEN LEN(FLOOR(COL3)) <= 2 THEN CONCAT(COL3,'%')
WHEN (LEN(FLOOR(COL3)) >= 4 AND LEN(FLOOR(COL3)) <=5) THEN FORMAT(FLOOR(COL3),'0,K')
WHEN LEN(FLOOR(COL3)) >= 4 THEN FORMAT(FLOOR(COL3),'0,,M')
END AS COL3
FROM
TABLE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.