Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the first N digits of an integer

Tags:

sql

sql-server

I have a SQL Server table ("Activities") which has a column containing an ID, e.g. "10553100". This is the activity ID and is composed of two parts -> first 4 digits indicates which project it belongs to, and the last 4 digits indicates which sub project.

I need to extract the project number from the activityId column (aka the first 4 digits). Is it possible to do this using a simple SELECT statement in SQL?

like image 618
msk Avatar asked Jun 17 '15 09:06

msk


People also ask

How do I find the first digit of an integer?

To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.

How do you find the first N digit of a number in Java?

pow(10, N) (preferably using a temporary variable), where N represents the number of decimal digits.

What is the first digit?

The first digit of any (natural) number takes the value of 1 to 9. It may seem intuitive to argue in the first instance that the first digit in a credible set of numbers is uniformly distributed.


4 Answers

Use the LEFT function.

SELECT activityId, LEFT(activityId, 4) AS projectnumber
FROM Activities

Or the SUBSTRING function.

SELECT activityId, SUBSTRING (activityId, 1, 4) AS projectnumber
FROM Activities

And if you want too include your subprojectnumber

LEFT and RIGHT functions.

SELECT activityId, LEFT(activityId, 4) AS projectnumber, RIGHT(activityId, 4) AS subprojectnumber
FROM Activities

SUBSTRING function.

SELECT activityId, SUBSTRING (activityId, 1, 4) AS projectnumber, SUBSTRING(activityId, 5, 4) AS subprojectnumber
FROM Activities
like image 160
Matt Avatar answered Nov 17 '22 17:11

Matt


Try this

Select left(activityId,4) from Activities
like image 23
Azar Avatar answered Nov 17 '22 17:11

Azar


If the field is numeric then:

SELECT Col / 10000 FROM TableName

If char the:

SELECT LEFT(Col, 4) FROM TableName
like image 37
Giorgi Nakeuri Avatar answered Nov 17 '22 17:11

Giorgi Nakeuri


The left command yould work:

SELECT LEFT(id, 4) FROM dbo.Activities
like image 39
Jens Avatar answered Nov 17 '22 16:11

Jens