I have table TableA as below
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.
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 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:
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; 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. If your SQLS supports FORMAT like FORMAT(column1/1000.0, '0.#K')
you should consider using it instead
You can use FORMAT function, but instead of hardcoding number, we can use like this. Though this kind of conversion should not be done at SQL Server and presentation application should handle this
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.