SQL - left pad with the zero after symbol '-' - sql

I am trying to left pad with a single zero after the '-'.
I did check the other answers here but didnt help me.
Here is the table :
+---------+
| Job |
+---------+
| 3254-1 |
| 3254-25 |
| 3254-6 |
+---------+
I need to left pad with single zero after '-' if the value is between 1 and 9 in the end
I want the results to be :
+---------+
| Job |
+---------+
| 3254-01 |
| 3254-25 |
| 3254-06 |
+---------+

You can use CHARINDEX(), SUBSTRING() and REPLACE() as:
CREATE TABLE Jobs(
Job VARCHAR(45)
);
INSERT INTO Jobs VALUES
('3254-1'),
('3254-25'),
('3254-6');
SELECT CASE
WHEN CHARINDEX('-', Job, 1)+1 < LEN(Job) THEN Job
ELSE
REPLACE(Job, '-', '-0')
END AS Job
FROM Jobs;
Results:
+----+---------+
| | Job |
+----+---------+
| 1 | 3254-01 |
| 2 | 3254-25 |
| 3 | 3254-06 |
+----+---------+

If you want an update, I think this is the simplest method:
update t
set job = replace(job, '-', '-0')
where job like '%-_';
This problem is simplified greatly because you are only adding a single padding character.

If you have version 2012+, then format function may be used as :
select concat(nr1, '-', format( cast ( q2.nr2 as int ), '00')) as result
from
(
select substring(q1.str,1,charindex('-',q1.str,1)-1) as nr1,
substring(q1.str,charindex('-',q1.str,1)+1,len(q1.str)) as nr2
from
(
select '3254-1' as str union all
select '3254-25' as str union all
select '3254-6' as str
) q1
) q2;
result
------
3254-01
3254-25
3254-06
Rextester Demo

Related

Oracle regex_replace ' from values

I need help wit removing "'pp'" from search results which appear at the biginning of text. Values in search resuls contain spaces and also '. I need to remove only 'pp from bigginig
This sounds like:
select regexp_replace(col, '^pp', '')
Or a case expression:
select (case when col like 'pp%' then substr(col, 3) else col end)
You don't need regular expressions and can use simple string functions.
If you want to use SELECT then:
SELECT value,
CASE
WHEN value LIKE 'pp%'
THEN SUBSTR( value, 3 )
ELSE value
END AS replaced_value
FROM table_name
Outputs:
VALUE | REPLACED_VALUE
:---- | :-------------
pp123 | 123
pp1pp | 1pp
123pp | 123pp
12345 | 12345
and, if you want to UPDATE the table:
UPDATE table_name
SET value = SUBSTR( value, 3 )
WHERE value LIKE 'pp%';
Then:
SELECT * FROM table_name;
Outputs:
| VALUE |
| :---- |
| 123 |
| 1pp |
| 123pp |
| 12345 |
db<>fiddle here

SQL padding 0 to the left of a number in string

I am a beginner in SQL language and I am using postgre sql and doing little exercices to learn. I have a column of strings named acronym from a destination table:
DO1
ES1
ES2
FR1
FR10
FR2
FR3
FR4
FR5
FR6
FR7
FR8
FR9
GP1
GP2
IN1
IN2
MU1
RU1
TR1
UA1
I would like to add a padding zero for acronym numbers that have only one digit, output:
DO01
ES01
ES02
FR01
FR02
FR03
FR04
FR05
FR06
FR07
FR08
FR09
FR10
GP01
GP02
IN01
IN02
MU01
RU01
TR01
UA01
How can I get to the left of the first number in the string? There is some regex I think but I did not figure it out
You can use the rpad() function to add characters to the end of the value:
select rpad(col, '0', 4)
In your case, though, you want a value in-between. On simple method is -- assuming that the first two characters are strings -- is:
(case when length(col) = 3
then left(col, 2) || '0' || right(col, 1)
else col
end)
Another possibility is using regexp_replace():
regexp_replace(col, '^([^0-9]{2})([0-9])$', '\10\2')
Both of these assume that the strings to be padded are three characters, which is consistent with your data. It is unclear what you want for other lengths.
try with below:
to_char() function
select to_char(column1, 'fm000') as column2
from Test_table;
fm "fill mode"prefix avoids leading spaces in the resulting var char.
000 it defines the number of digits you want to have.
You can use string functions like lpad(), substr(), left():
select
concat(left(columnname, 2), lpad(substr(columnname, 3), 2, '0')) result
from tablename
See the demo.
Results:
| result |
| ------ |
| DO01 |
| ES01 |
| ES02 |
| FR01 |
| FR10 |
| FR02 |
| FR03 |
| FR04 |
| FR05 |
| FR06 |
| FR07 |
| FR08 |
| FR09 |
| GP01 |
| GP02 |
| IN01 |
| IN02 |
| MU01 |
| RU01 |
| TR01 |
| UA01 |

Delete redundant suffix or move it to another column

I have table like this
-----------------------------------
| id | col_name | colname_suf |
-----------------------------------
| 1 | textSuff_ix| null |
| 2 | strSuff_ix2| null |
| ... |
-----------------------------------
The main idea of my solution is to move suffix to another column. But suffix and text before can be in known range(text1, text2, str, Suff_ix1, Suff_ix2, Suff_ix3...). How i can fix it using sql query?
Use string functions like left(), right() and charindex() to split the column and update:
update tablename
set [col_name] = left([col_name], charindex('_', [col_name]) - 1),
[colname_suf] = right([col_name], len([col_name]) - charindex('_', [col_name]))
where [col_name] like '%[_]%';
See the demo.
Results:
> id | col_name | colname_suf
> -: | :------- | :----------
> 1 | textSuff | ix
> 2 | strSuff | ix2
You can use string operations:
select left(col_name, charindex('_', col_name) - 1) as prefix,
stuff(col_name, 1, charindex('_', col_name), '') as suffix

Padding to the result of a DISTINCT Sqlite query

I searched and figured out that I could use either substr with || or a printf statement with format specifiers in order to add padding to the results, but that doesn't seem to work if I had DISTINCT in the sqlite query.
I've a table called timeLapse that looks like so:
+----+-------+-----------+
| ID | Time | Status |
+----+-------+-----------+
| 1 | 0.001 | Initiated |
| 1 | 0.002 | Cranked |
| 3 | 0.002 | Initiated |
| 2 | 0.002 | Initiated |
| 2 | 0.003 | Cranked |
+----+-------+-----------+
I could query the distinct IDs with something like SELECT distinct(ID) FROM timeLapse as IDs, which returns this:
+-----+
| IDs |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
However, I would like to pad the resultant distinct rows like so:
+----------+
| IDs |
+----------+
| Object-1 |
| Object-2 |
| Object-3 |
+----------+
My query SELECT substr('Object-' || DISTINCT(ID), 10, 10) as IDs FROM timeLapse results in an error:
"[17:22:47] Error while executing SQL query on database 'machining': near "distinct": syntax error"
Could someone please help me understand what am I doing wrong here? I am enormously thankful for your time and help.
get distinct() first before using substr() function.
select substr('Object-' || t1.ID, 1, 10) as IDs
from (SELECT DISTINCT(ID) ID FROM timeLapse) t1
see sqlfiddle
All credits to the user named ϻᴇᴛᴀʟ, as I only understood from their answer that I should have a sub-query within this query where the DISTINCT should go into.
This resolves my problem:
select printf('Object-%s', t1.ID) as IDs
FROM (SELECT DISTINCT(id) ID FROM timeLapse) t1

Get row with max value in Hive/SQL?

I'm new to Hive/SQL, and I'm stuck on a fairly simple problem. My data looks like:
+------------+--------------------+-----------------------+
| carrier_iD | meandelay | meancanceled |
+------------+--------------------+-----------------------+
| EV | 13.795802119653473 | 0.028584251044292006 |
| VX | 0.450591016548463 | 2.364066193853424E-4 |
| F9 | 10.898001378359766 | 0.00206753962784287 |
| AS | 0.5071547420965062 | 0.0057404326123128135 |
| HA | 1.2031093279839498 | 5.015045135406214E-4 |
| 9E | 8.147899230704216 | 0.03876067292247866 |
| B6 | 9.45383857757506 | 0.003162096314343487 |
| UA | 8.101511665305816 | 0.005467725574605967 |
| FL | 0.7265068895709532 | 0.0041141513746490044 |
| WN | 7.156119279121648 | 0.0057419058192869415 |
| DL | 4.206288692245839 | 0.005123990066804269 |
| YV | 6.316802855264404 | 0.029304029304029346 |
| US | 3.2221527095063736 | 0.007984031936127766 |
| OO | 6.954715814690328 | 0.02596499362466706 |
| MQ | 9.74568222216328 | 0.025628100708354324 |
| AA | 8.720522654298968 | 0.019242775597574157 |
+------------+--------------------+-----------------------+
I want Hive to return the row with the meanDelay max value. I have:
SELECT CAST(MAX(meandelay) as FLOAT) FROM flightinfo;
which indeed returns the max (I use cast because my values are saved as STRING). So then:
SELECT * FROM flightinfo WHERE meandelay = (SELECT CAST(MAX(meandelay) AS FLOAT) FROM flightinfo);
I get the following error:
FAILED: ParseException line 1:44 cannot recognize input near 'select' 'cast' '(' in expression specification
Use the windowing and analytics functions
SELECT carrier_id, meandelay, meancanceled
FROM
(SELECT carrier_id, meandelay, meancanceled,
rank() over (order by cast(meandelay as float) desc) as r
FROM table) S
WHERE S.r = 1;
This will also solve the problem if more than one row has the same max value, you'll get all the rows as result. If you just want a single row change rank() to row_number() or add another term to the order by.
use join instead.
SELECT a.* FROM flightinfo a left semi join
(SELECT CAST(MAX(meandelay) AS FLOAT)
maxdelay FROM flightinfo)b on (a.meandelay=b.maxdelay)
You can use the collect_max UDF from Brickhouse ( http://github.com/klout/brickhouse ) to solve this problem, passing in a value of 1, meaning that you only want the single max value.
select array_index( map_keys( collect_max( carrier_id, meandelay, 1) ), 0 ) from flightinfo;
Also, I've read somewhere that the Hive max UDF does allow you to access other fields on the row, but I think its easier just to use collect_max.
I don't think your sub-query is allowed ...
A quick look here:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries
states:
As of Hive 0.13 some types of subqueries are supported in the WHERE
clause. Those are queries where the result of the query can be treated
as a constant for IN and NOT IN statements (called uncorrelated
subqueries because the subquery does not reference columns from the
parent query):