TSQL round number and check in which group it is - sql

I have a quite simple task:
I must check in wchich group my float is.
Here are my groups:
0-30 display "(0-30)"
30-40 display "(0-30)"
40-50 display "(0-30)"
50-60 display "(0-30)"
etc
I have created a simple script:
DECLARE #num FLOAT
SET #num = 42.5;
SELECT CASE WHEN #num<=30 THEN '(0-30)'
ELSE '('+convert(VARCHAR,convert(INT,round((#num/10),0))*10)+'-'+convert(VARCHAR,convert(INT,round(((#num+10)/10),0))*10)+')'
END
I think it is a little lame, so if anyone could help me out with creating a better solution :)
Thanks for any advice :)

Use:
DECLARE #num FLOAT
SET #num = 311.2;
SELECT
CASE
WHEN #num <= 30
THEN '(0-30)'
ELSE '(' + cast(cast(#num AS INT) / 10 * 10 AS VARCHAR) + '-' + cast(cast(#num AS INT) / 10 * 10 + 10 AS VARCHAR) + ')' END

Or you can use: (to get rid of the CASE statement and get a more readable look, IMO)
declare #num float = 156
select
'(' + convert(varchar, lowLimit) + ' - ' + convert(varchar, highLimit) + ')'
from
(
select
0 as lowLimit,
30 as highLimit
where
#num <= 30
union all
select
floor(#num/10)*10,
ceiling(#num/10)*10
where
#num > 30
) limits

Related

How to add leading zero when number is less than 10?

I have a column in my sql table. I am wondering how can I add leading zero to my column when my column's value is less than 10? So for example:
number result
1 -> 01
2 -> 02
3 -> 03
4 -> 04
10 -> 10
format(number,'00')
Version >= 2012
You can use RIGHT:
SELECT RIGHT('0' + CAST(Number AS VARCHAR(2)), 2) FROM tbl
For Numbers with length > 2, you use a CASE expression:
SELECT
CASE
WHEN Number BETWEEN 0 AND 99
THEN RIGHT('0' + CAST(Number AS VARCHAR(2)), 2)
ELSE
CAST(Number AS VARCHAR(10))
END
FROM tbl
Felix's solution is great, unless you have numbers above 100 in your table, in which case, try using a case statement instead:
Select case when Number between 1 and 9
then '0' else '' end + cast(number as varchar(3))
And yet one more solution:
SELECT REPLACE(STR(#YourNumber,2),' ','0');
I prefer this, as other approaches might lead to random results in case of numbers which are wider than the count of digits you've specified:
But it will not deal with negativ numbers...
DECLARE #YourNumber INT=123;
SELECT REPLACE(STR(#YourNumber,5),' ', '0') --pad to five digits
,REPLACE(STR(#YourNumber,3),' ', '0') --pad to 3 digits
,REPLACE(STR(#YourNumber,2),' ', '0'); --123 is wider than 2 digits...
The result
00123
123
**
another method,
select case when number <10 then replicate('0',1)+cast(number as varchar)
else cast(number as varchar) end
In another method, you can Replace 10 to 2.
declare #ID int =32123;
substring('000000000',1,10-len(cast(#ID as varchar(10)))) + cast(#Id as varchar(10))
Result:
0000032123

Concatenation not working inside of function in SQL Server

I am converting minutes to days and hours. When I am using following code, it works fine
declare #theMinutes int
Set #theMinutes = 1449
select cast(#theMinutes / 1440 as varchar)
+ ' Day(s) '+ cast((#theMinutes % 1440 / 60) as varchar)
+ ' Hour(s) '+ cast(#theMinutes % 60 as varchar)
+ ' Minute(s)' AS COLUMN_A
and displays result
1 Day(s) 0 Hour(s) 9 Minute(s)
But when I use this to write a function, then it is only returning 1, the rest things are not getting concatenated
Create function [dbo].[ConvertMinToDays]
(
#theMinutes int
)
RETURNS varchar
AS
BEGIN
Declare #convertedStr varchar(200)
SET #convertedStr = cast(#theMinutes / 1440 as varchar(10)) + ' Day(s) '
+ cast((#theMinutes % 1440 / 60) as varchar(10))+ ' Hour(s) '
+ cast(#theMinutes % 60 as varchar(10)) + ' Minute(s)';
return #convertedStr;
END
GO
SELECT dbo.ConvertMinToDays(1449) as COLUMN_A
Can Anybody help me , where i am going wrong ??
Change
RETURNS varchar
to
RETURNS varchar(200)
I'm assuming its only going to return one character otherwise
You are returning a varchar
Change it to
RETURNS varchar(200)

Cap field value in SELECT

I am trying to cap particular fields so that they don't exceed a particular value.
For example, something like this would suffice, where I can specify that a field should not exceed 8:
SELECT (
cap(t.MondayHrs,8)
+ cap(t.TuesdayHrs,8)
+ cap(t.WednesdayHrs,8)
+ cap(t.ThursdayHrs,8)
+ cap(t.FridayHrs,8)
) as TotalHours
If MondayHrs = 7, then it should be added to TotalHours as 7.
If MondayHrs = 10, then it should be added to TotalHours as 8 (my capped value)
Is there anything built into T-SQL that could facilitate this?
create function Cap (#Value float,#maxValue float) Returns float
as
begin
Declare #Result float
if #Value > #maxValue select #Result=#Maxvalue else select #Result=#Value
Return #Result
end;
usage
Select dbo.Cap(1,10),dbo.Cap(11,10)
Try...
select least(t.MondayHrs,8)
+ least(t.TuesdayHrs,8)
+ least(t.WednesdayHrs,8)
+ least(t.ThursdayHrs,8)
+ least(t.FridayHrs,8)
) as TotalHours
An alternate idea would be to use CASE. For example:
SELECT (
(CASE WHEN t.MondayHrs > 8 THEN 8 ELSE t.MondayHrs END)
+ (CASE WHEN t.TuesdayHrs > 8 THEN 8 ELSE t.TuesdayHrs END)
) as TotalHours
You can write a function for that like MySQL GREATEST.
Then you could do something like
select greatest(some_col, 8) +
greatest(other_col, 8) +
...
from your_table

How to display the number “12” in the format of “0000012”

How to display the number “12” in the format of “0000012” Using SQL
if you just want the number 12 then
SELECT '0000012'
else if it is a number you need to display with 7 digits:
SELECT RIGHT('0000000'+CONVERT(nvarchar,FieldValue),7)
More info on the question would help.
How about something like
DECLARE #Val INT
DECLARE #Length INT
SELECT #Val = 12,
#Length = 7
SELECT REPLICATE('0',#Length - LEN(CAST(#Val AS VARCHAR(MAX)))) + CAST(#Val AS VARCHAR(MAX))
REPLICATE (Transact-SQL)
Repeats a string value a specified
number of times.
The shortest answer that probably also works best is just
SELECT RIGHT(10000000+ #Val, #Length)
e.g.
SELECT RIGHT(10000000+ NumColumn, 7)
I haven't got a server to test with, but you should be able to use the following in your SQL:
'RN ' + RIGHT(CAST(auto_id AS VarChar) + '000000', 6)
eg:
Code:
SELECT 'RN ' + RIGHT(CAST(auto_id AS VarChar) + '000000', 6)
FROM tablename
This is not efficient but will work for your case -
DECLARE #num int
DECLARE #totalChar int
SET #num = 12
SET #totalChar = 10
SELECT right('0000000000' + CONVERT(varchar, #num), #totalChar)
Output -
000000012
This should easily port to other SQLs:
SELECT
REVERSE(CAST(REVERSE(CAST(CAST(12 AS INTEGER) AS VARCHAR(7))) + '000000' AS CHAR(7)))
SELECT REPLACE(STR(12, 7), ' ', '0')

t-sql: return range in which a given number falls

I am trying to figure out a good way to return a string 'name' of a range in which a given number falls. Ranges are spans of 1000, so the first range is '0000-0999', the second is '1000-1999' etc. For example, given the number 1234, I want to return the literal string '1000-1999'.
It seems to me that I could maintain a reference table with these ranges, like this
--create & populate temp table with ranges
create table #ranges (st int,en int)
go
insert into #ranges values(0,999)
insert into #ranges values(1000,1999)
insert into #ranges values(2000,2999)
go
--example query
select replace(str(st,4),' ','0') + '-' + replace(str(en,4),' ','0') as TheStringIWant
from #ranges
where 1234 between st and en
...but it seems to me that the ranges should be able to be determined from the given number itself, and that I shouldn't need the (redundant) reference table (or, for that matter, a function) just for this.
It also seems to me that I should be able to figure this out with just a bit of brain power, except that I've just had 2 beers in quick succession this evening...
Another way;
select case when value / 1000 < 1
then '0000-0999'
else cast(value / 1000 * 1000 as varchar(16)) + '-' + cast(value / 1000 * 1000 + 999 as varchar(16))
end
You can use mathematical functions to avoid using the temp table:
SELECT 1234,
RIGHT('0000' + CAST(FLOOR(1234/1000.0) * 1000 AS VARCHAR(11)),4)
+ '-'
+ RIGHT('0000' + CAST( (FLOOR(1234/1000.0) * 1000) + 999 AS VARCHAR(11)),4)
In the shell, I can use integer-arithmetic to cut off the 234, and calculate the string with a simple formular, however it wouldn't produce 0000-0999 but 0-999 for the first 1000.
v=1234
echo $(((v/1000)*1000))-$(((v/1000)*1000+999))
1000-1999
I don't know how to adapt it to tsql - whether possible at all.
declare #range int;
set #range = 1000;
select replace(str(st,4),' ','0') + '-' +
replace(str(st + #range,4),' ','0') as TheStringIWant
from (
select st = v / #range * #range
from (select v = 1234) s
) s