I have a table that has a column with 1 to 3 digits.
For example:
(342) 342-9324
(1) 234-3424
(04) 234-7744 etc
But I am not sure how to write the query. I use
SUBSTRING(x, 2, 3)
where x is name of column, but I only get 3 digits, anyone have any ideas to extract digits in brackets that could be 1, 2 or 3 digits? This is done using sql server. Also this table has more than 5 million rows of phone numbers
If area code is within (), some simple string functions should do.
Example
Declare #YourTable Table ([Phone] varchar(50)) Insert Into #YourTable Values
('(342) 342-9324')
,('(1) 234-3424')
,('(04) 234-7744')
Select *
,AreaCode = replace(left(Phone,charindex(')',Phone+')')-1),'(','')
From #YourTable
Returns
Phone AreaCode
(342) 342-9324 342
(1) 234-3424 1
(04) 234-7744 04
Related
Say I have a table with an incrementing id column and a random positive non zero number.
id
rand
1
12
2
5
3
99
4
87
Write a query to return the rows which add up to a given number.
A couple rules:
Rows must be "consumed" in order, even if a later row makes it a a perfect match. For example, querying for 104 would be a perfect match for rows 1, 2, and 4 but rows 1-3 would still be returned.
You can use a row partially if there is more available than is necessary to add up to whatever is leftover on the number E.g. rows 1, 2, and 3 would be returned if your max number is 50 because 12 + 5 + 33 equals 50 and 90 is a partial result.
If there are not enough rows to satisfy the amount, then return ALL the rows. E.g. in the above example a query for 1,000 would return rows 1-4. In other words, the sum of the rows should be less than or equal to the queried number.
It's possible for the answer to be "no this is not possible with SQL alone" and that's fine but I was just curious. This would be a trivial problem with a programming language but I was wondering what SQL provides out of the box to do something as a thought experiment and learning exercise.
You didn't mention which RDBMS, but assuming SQL Server:
DROP TABLE #t;
CREATE TABLE #t (id int, rand int);
INSERT INTO #t (id,rand)
VALUES (1,12),(2,5),(3,99),(4,87);
DECLARE #target int = 104;
WITH dat
AS
(
SELECT id, rand, SUM(rand) OVER (ORDER BY id) as runsum
FROM #t
),
dat2
as
(
SELECT id, rand
, runsum
, COALESCE(LAG(runsum,1) OVER (ORDER BY id),0) as prev_runsum
from dat
)
SELECT id, rand
FROM dat2
WHERE #target >= runsum
OR #target BETWEEN prev_runsum AND runsum;
I am looking for a simple clean method to obtain the sequence {1, 2, 3, 4, 5, 6, 7,...,1000000} in MS Access SQL. I thought of creating a table with a column that numbers from 1 to 100000 however, this is inefficient.
Is there a way of generating numbers 1 to 10000000 in MS Access using SQL?
I tried the GENERATE_SERIES() function but MS Access SQL does not support this function.
id | number
------------
1. | 1
2. | 2
3. | 3
4. | 4
5. | 5
6. | 6
7. | 7
8. | 8
Yes, and it is not painfull - use a Cartesian query.
First, create a small query returning 10 records:
SELECT
DISTINCT Abs([id] Mod 10) AS N
FROM
MSysObjects;
Save it as Ten.
Then run this simple query:
SELECT
[Ten_0].[N]+[Ten_1].[N]*10+[Ten_2].[N]*100+[Ten_3].[N]*1000+[Ten_4].[N]*10000+[Ten_5].[N]*100000 AS Id
FROM
Ten AS Ten_0,
Ten AS Ten_1,
Ten AS Ten_2,
Ten AS Ten_3,
Ten AS Ten_4,
Ten AS Ten_5
which, in two seconds, will return Id from 0 to 999999.
Very painful but you can do the following:
create table numbers (
id int autoincrement,
number int
);
-- 1 row
insert into numbers (number) values (1);
-- 2 rows
insert into numbers (number) select number from numbers;
-- 4 rows
insert into numbers (number) select number from numbers;
-- 8 rows
insert into numbers (number) select number from numbers;
-- repeat a total of 20 times
The value of number is always 1, but id increments. You can make them equal using an update:
update numbers
set number = id;
If this were SQL server you could use a recursive CTE to do this.
WITH number
AS
(
SELECT num = 1
UNION ALL
SELECT num + 1
from number
where num < 1000000
)
SELECT num FROM number
option(maxrecursion 0)
But you are asking about MS Access, since access does not support recursive CTEs, you can try doing it with a macro and insert it into a table and read it out?
I need to return matches that are with a range of serial numbers but the prefix and suffix need to be removed
Ie. I need to search between the below serial numbers but the sequential numbers are only the middle part.
G4A41103801702 - G4A41113171702
G4A [4110380] 1702 - G4A [4111317] 1702
I need to exclude the first 3 and last 4 digits and then search between
4110380-4111317
thanks
baton, try a variation of the query below:
Replace id with the column you want to select.
Replace tablename with your actual table name.
Assumes serialnumber is the name of the column with the serial to be queried against.
Assumes the length of the serial number is constant.
SELECT id FROM tablename WHERE
CAST(SUBSTRING(serialnumber, 4, 7) as int) >= 4110380 AND
CAST(SUBSTRING(serialnumber, 4, 7) as int) <= 4111317
As #ADyson mentioned, this will not utilize an index and you should extract this number into a separate indexed column for a more performant query. Hope this helps!
If length is not constant, you can combine reverse function twice time to exclude the first 3 and last 4 digits:
SELECT id FROM tablename WHERE
substring(reverse(substring(reverse(serialnumber),5)),4) >= 4110380 AND
substring(reverse(substring(reverse(serialnumber),5)),4) <= 4111317
test :
substring(reverse(substring(reverse('G4A41103801702'),5)),4) ==> '4110380'
I'd handle this like so:
-- Sample data
DECLARE #table TABLE (col1 VARCHAR(100));
INSERT #table (col1)
VALUES ('G4A41103801702 - G4A41113171702');
-- solution
SELECT
c1=SUBSTRING(s.s1,PATINDEX(p.P,s.s1),7),
c2=SUBSTRING(s.s2,PATINDEX(p.P,s.s2),7)
FROM #table AS t
CROSS JOIN (VALUES('%'+REPLICATE('[0-9]',7)+'%')) AS p(P)
CROSS APPLY (VALUES(CHARINDEX('-',t.col1))) AS br(b)
CROSS APPLY (VALUES(SUBSTRING(t.col1,1,br.b-1),
SUBSTRING(t.col1,br.b+1,8000))) AS s(s1,s2);
Returns:
c1 c2
------- -------
4110380 4111317
You can then use c1 and c2 elsewhere.
I need to order string containing this format
number .(dot) number .(dot) number .(dot) number and so on multiple levels so the string can be
1.1.1.1.1.1.5
or
1.1.1.1.1.1.1.1.1.1.1.1.1.1......9
or
5
or
5.5.6.7.8.1.2.3454.2.11213
I have tried doing cast, but i need a solution other than common table expresions, because it is pretty slow.
is there a way to order this like numbers so 10 be next to 9 and not to 1, thank you
This works, with a few assumptions, one being that the first digit always is an int.
insert into #t values ('1.0'),
('10.2.44.2'),
('5.2.523.242'),
('4.23.5511'),
('0.9.4343.1.6.2'),
('99.245.52371.0.1'),
('1.1.1.1.1.1.5'),
('1.1.1.1.1.1.1.1.1.1.1.1.1.1......9'),
('5.5'),
('5.5.6.7.8.1.2.3454.2.11213')
SELECT CAST(SUBSTRING(c, 0, COALESCE(CHARINDEX('.',c, 0), c)) AS INT) AS FirstDigit, c
from #t
order by FirstDigit
Results:
FirstDigit c
0 0.9.4343.1.6.2
1 1.0
1 1.1.1.1.1.1.5
1 1.1.1.1.1.1.1.1.1.1.1.1.1.1......9
4 4.23.5511
5 5.2.523.242
5 5.5
5 5.5.6.7.8.1.2.3454.2.11213
10 10.2.44.2
99 99.245.52371.0.1
I have one table that stores a range of integers in a field, sort of like a print range, (e.g. "1-2,4-7,9-11"). This field could also contain a single number.
My goal is to join this table to a second one that has discrete values instead of ranges.
So if table one contains
1-2,5
9-15
7
And table two contains
1
2
3
4
5
6
7
8
9
10
The result of the join would be
1-2,5 1
1-2,5 2
1-2,5 5
7 7
9-15 9
9-15 10
Working in SQL Server 2008 R2.
Use a string split function of your choice to split on comma. Figure out the min/max values and join using between.
SQL Fiddle
MS SQL Server 2012 Schema Setup:
create table T1(Col1 varchar(10))
create table T2(Col2 int)
insert into T1 values
('1-2,5'),
('9-15'),
('7')
insert into T2 values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
Query 1:
select T1.Col1,
T2.Col2
from T2
inner join (
select T1.Col1,
cast(left(S.Item, charindex('-', S.Item+'-')-1) as int) MinValue,
cast(stuff(S.Item, 1, charindex('-', S.Item), '') as int) MaxValue
from T1
cross apply dbo.Split(T1.Col1, ',') as S
) as T1
on T2.Col2 between T1.MinValue and T1.MaxValue
Results:
| COL1 | COL2 |
----------------
| 1-2,5 | 1 |
| 1-2,5 | 2 |
| 1-2,5 | 5 |
| 9-15 | 9 |
| 9-15 | 10 |
| 7 | 7 |
Like everybody has said, this is a pain to do natively in SQL Server. If you must then I think this is the proper approach.
First determine your rules for parsing the string, then break down the process into well-defined and understood problems.
Based on your example, I think this is the process:
Separate comma separated values in the string into rows
If the data does not contain a dash, then it's finished (it's a standalone value)
If it does contain a dash, parse the left and right sides of the dash
Given the left and right sides (the range) determine all the values between them into rows
I would create a temp table to populate the parsing results into which needs two columns:
SourceRowID INT, ContainedValue INT
and another to use for intermediate processing:
SourceRowID INT, ContainedValues VARCHAR
Parse your comma-separated values into their own rows using a CTE like this Step 1 is now a well-defined and understood problem to solve:
Turning a Comma Separated string into individual rows
So your result from the source
'1-2,5'
will be:
'1-2'
'5'
From there, SELECT from that processing table where the field does not contain a dash. Step 2 is now a well-defined and understood problem to solve These are standalone numbers and can go straight into the results temp table. The results table should also get the ID reference to the original row.
Next would be to parse the values to the left and right of the dash using CHARINDEX to locate it, then the appropriate LEFT and RIGHT functions as needed. This will give you the starting and ending value.
Here is a relevant question for accomplishing this step 3 is now a well-defined and understood problem to solve:
T-SQL substring - separating first and last name
Now you have separated the starting and ending values. Use another function which can explode this range. Step 4 is now a well-defined and understood problem to solve:
SQL: create sequential list of numbers from various starting points
SELECT all N between #min and #max
What is the best way to create and populate a numbers table?
and, also, insert it into the temp table.
Now what you should have is a temp table with every value in the exploded range.
Simply JOIN that to the other table on the values now, then to your source table on the ID reference and you're there.
My suggestion is to add one more field and many more records to your ranges table. Specifically, the primary key would be the integer and the other field would be the range. Records would look like this:
number range
1 1-2,5
2 1-2,5
3 na
4 na
5 1-2,5
etc
Having said that, this is still rather limiting because a number can only have one range. If you want to be thorough, set up a many to many relationship between numbers and ranges.
As far as I can tell you best option is something like below:
Create a table value function that accepts your ranges an converts them to a collection of ints. So 1-3,5 would return:
1
2
3
5
Then use these results to join to other tables. I don't have an exact function to do this at hand, but this one seems like an excellent start.