How I can get the first 3 digits in 123456 Numbers in sql?
Asked Answered
G

5

8

I have field called CallingParty in My CDR table it contains data like this:

CallingParty
------------
267672668788

I want to select the first 3 number of each of those numbers like

CallingParty
------------
267
Guttersnipe answered 31/5, 2012 at 6:57 Comment(2)
possible duplicate of SQL: how to get the left 3 numbers from an intPegu
Does this answer your question? SQL: how to get the left 3 numbers from an intHomogenous
P
14

if CallingParty is of type int:

SELECT CAST(LEFT(CallingParty, 3) AS INT)
From CDR
Pod answered 31/5, 2012 at 7:1 Comment(2)
No need to CAST explicitly, LEFT(123456,3) will do an implicit cast anyway.Cusec
That wasn't the cast I meant! Your edit has broken your answer as now you have a dangling AS INT I meant the cast to varchar as input to the LEFT function. Some people might prefer the explicit cast anyway but I find it more readable/less noisy without.Cusec
V
2

SQL Server has a Left() function, but it works best on strings. (varchar/char in SQL)

Select left(cast(267672668788 as varchar), 3)
Vanhook answered 31/5, 2012 at 7:3 Comment(1)
left is more readable, and less confusing especially when some systems start at 0 and some at 1. KISSRender
S
1

Use this query:

SELECT SUBSTRING(CAST(CallingParty AS VARCHAR(50)), 1, 3) FROM [CDR]
Schade answered 31/5, 2012 at 7:2 Comment(0)
S
1

If the data length does not change then you can always divide by 10 * the digits you have

SELECT FLOOR(267672668788 / 1000000000)
=267
Salvadorsalvadore answered 7/4, 2017 at 15:29 Comment(0)
P
-1

Try this:

SELECT Substring(callingparty, 1, Length(callingparty) - 9) 
FROM   cdr; 
Patman answered 17/1, 2019 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.