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?
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.
pow(10, N) (preferably using a temporary variable), where N represents the number of decimal digits.
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.
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
Try this
Select left(activityId,4) from Activities
If the field is numeric then:
SELECT Col / 10000 FROM TableName
If char the:
SELECT LEFT(Col, 4) FROM TableName
The left command yould work:
SELECT LEFT(id, 4) FROM dbo.Activities
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With