How to sort string with numbers numerically in SQL? - sql

this is how it is currently sorted:
CRI-SU1
CRI-SU10
CRI-SU11
CRI-SU2
CRI-SU3
CRI-SU4
CRI-SU5
CRI-SU6
CRI-SU7
CRI-SU8
CRI-SU9
I wanted it to be sorted numerically like:
CRI-SU1
CRI-SU2
CRI-SU3
CRI-SU4
CRI-SU5
CRI-SU6
CRI-SU7
CRI-SU8
CRI-SU9
CRI-SU10
CRI-SU11
How do you sort it in SQL?
this is my sql statement...
SELECT systemUnitID FROM systemUnit ORDER BY systemUnitID

If the prefix always reads "CRI-SU", you can try to replace it with the empty string by using replace(). Then cast the result to an integer with cast() and order by the casted value. This should work in many DBMS.
SELECT systemunitid
FROM systemunit
ORDER BY cast(replace(systemunitid, 'CRI-SU', '') AS integer);

SELECT systemUnitID
FROM systemUnit
ORDER BY CAST(REPLACE(systemUnitID, 'CRI-SU', '') As int)

Related

how can I convert a number to a string, extract each digit, cast it again to integers, and add them all together (e.g. 1+2+3+4+5+6) in SQL?

I'm thinking I have to create a view that stores the cast as text and I have to utilize the substring function in sql but I'm a little lost. Any help would be greatly appreciated?
You can convert a string to rows using unnest() and string_to_array() and then add the digits using sum()
select sum(digit::int)
from unnest(string_to_array(12345::text, null)) as x(digit)
You can format the number
select to_char(12345, '0+0+0+0+0+0+0');
to_char
----------------
0+0+1+2+3+4+5
Inside a function, you can run this statement as a dynamic query to get the result
EXECUTE 'SELECT ' || to_char(12345, '0+0+0+0+0+0+0');
You can use a recursive CTE:
WITH RECURSIVE qsum AS (
SELECT 123456 AS num,
0 AS sum
UNION ALL
SELECT num / 10,
sum + num % 10
FROM qsum
WHERE num > 0
)
SELECT max(sum)
FROM qsum;
max
═════
21
(1 row)
You can get there with regexp_split_to_table, using ?!^ to split on every character.
regexp_split_to_table(cast(<your column> as text),'(?!^)') as s
Here's a simple Fiddle
You can shred the string to rows, then sum:
SELECT SUM(CAST(n as INTEGER))
FROM regexp_split_to_table('01234567', '') as n
But this sort of string math is probably a better fit for calling code. If you are trying to validate new records, consider doing it outside of the DB.

sql how to order by whether a string is found within a column?

so I aggregrate some strings (with either array_agg or string_agg) and put it in a new column.
I then want to:
order by ("searchString" in columnName)
However, it appears "in" is a keyword only working in where clauses. What should I use instead?
edit:
got it to work using bool_or
just used select bool_or(columnName = 'keyword') from and then ordered by the new column
You can use bool_or() assuming you want an exact match:
order by bool_or(col = <search_string>)
If you want a partial match, you can use like or regular expressions instead.
You can use position():
order by position('searchString' in columnName)
but if columnName is comma delimited:
order by position(',searchString,' in concat(',', columnName, ','))
position() returns 0 if the 'searchString' is not found inside columnName.
In this case maybe you need a case statement:
order by case position(',searchString,' in concat(',', columnName, ','))
when 0 then 9999 -- or any other large number
else position(',searchString,' in concat(',', columnName, ','))
end

Order the nvarchar values in SQL

When trying to order with the query
SELECT ACTT
FROM AIKUcusSaatleri
ORDER BY ACTT
this function not working properly. The result is shown below;
ACTT
0
1040
1042,6
873,8
996,6
996,6
997,6
What is the reason of this problem?
Greetings and thanks in advance.
But these are ordered correctly . . . If you realize that they are strings.
Store numbers as numbers. If you want to sort strings as numbers, you need to convert them. You can try:
order by cast(actt as numeric(20, 2))
That may or may not work with the comma, depending on your database and internationalization settings. It should work if you replace the comma with a decimal point:
order by cast(replace(actt, ',', '.') as numeric(20, 2))
There is no function available with your code, order by is a clause & perhaps you need :
Assuming the SQL Server DBMS if so, then you can do :
SELECT ACTT
FROM AIKUcusSaatleri
ORDER BY LEFT(ACCT, CHARINDEX(',', ACTT)-1);
if , treat as decimal ., then you need to do conversations :
SELECT ACTT
FROM AIKUcusSaatleri
ORDER BY CAST(REPLACE(ACTT, ',', '.') AS NUMERIC(20, 2));

Concatenate & Trim String

Can anyone help me, I have a problem regarding on how can I get the below result of data. refer to below sample data. So the logic for this is first I want delete the letters before the number and if i get that same thing goes on , I will delete the numbers before the letter so I can get my desired result.
Table:
SALV3000640PIX32BLU
SALV3334470A9CARBONGRY
TP3000620PIXL128BLK
Desired Output:
PIX32BLU
A9CARBONGRY
PIXL128BLK
You need to use a combination of the SUBSTRING and PATINDEX Functions
SELECT
SUBSTRING(SUBSTRING(fielda,PATINDEX('%[^a-z]%',fielda),99),PATINDEX('%[^0-9]%',SUBSTRING(fielda,PATINDEX('%[^a-z]%',fielda),99)),99) AS youroutput
FROM yourtable
Input
yourtable
fielda
SALV3000640PIX32BLU
SALV3334470A9CARBONGRY
TP3000620PIXL128BLK
Output
youroutput
PIX32BLU
A9CARBONGRY
PIXL128BLK
SQL Fiddle:http://sqlfiddle.com/#!6/5722b6/29/0
To do this you can use
PATINDEX('%[0-9]%',FieldName)
which will give you the position of the first number, then trim off any letters before this using SUBSTRING or other string functions. (You need to trim away the first letters before continuing with the next step because unlike CHARINDEX there is no starting point parameter in the PATINDEX function).
Then on the remaining string use
PATINDEX('%[a-z]%',FieldName)
to find the position of the first letter in the remaining string. Now trim off the numbers in front using SUBSTRING etc.
You may find this other solution helpful
SQL to find first non-numeric character in a string
Try this it may helps you
;With cte (Data)
AS
(
SELECT 'SALV3000640PIX32BLU' UNION ALL
SELECT 'SALV3334470A9CARBONGRY' UNION ALL
SELECT 'SALV3334470A9CARBONGRY' UNION ALL
SELECT 'SALV3334470B9CARBONGRY' UNION ALL
SELECT 'SALV3334470D9CARBONGRY' UNION ALL
SELECT 'TP3000620PIXL128BLK'
)
SELECT * , CASE WHEN CHARINDEX('PIX',Data)>0 THEN SUBSTRING(Data,CHARINDEX('PIX',Data),LEN(Data))
WHEN CHARINDEX('A9C',Data)>0 THEN SUBSTRING(Data,CHARINDEX('A9C',Data),LEN(Data))
ELSE NULL END AS DesiredResult FROM cte
Result
Data DesiredResult
-------------------------------------
SALV3000640PIX32BLU PIX32BLU
SALV3334470A9CARBONGRY A9CARBONGRY
SALV3334470A9CARBONGRY A9CARBONGRY
SALV3334470B9CARBONGRY NULL
SALV3334470D9CARBONGRY NULL
TP3000620PIXL128BLK PIXL128BLK

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'