i have a table T
id val1
a 199.87
b 166.56
c 100.67
d 233.45
e 177.23
I want to select those rows where val1 starts with 1
rows where val1 starts with 19.
Is there any way of doing this in SQL Server.
The data type of val1 is float.
1) I want to select those rows where val1 starts with 1
SELECT
*
FROM Table_1
WHERE val1 LIKE '1%'
2) rows where val1 starts with 19.
SELECT
*
FROM Table_1
WHERE val1 LIKE '19%'
You can use CONVERT or cast function in where clause to cast float to character data type . Below queries will generate your desired result.
select * from table1
where convert(varchar,val) like '1%';
select * from table1
where cast(val as char(10)) like '1%';
You can use anyone of the above.
Result
id val
-----------
a 199,87
b 166,56
c 100,67
e 177,23
To return val like 19, just replace 1 with 19.
You can check the demo here
If your data values will never exceed 200 it would be preferable not to convert them to another data type just to answer this query. Instead leave them as floats and assess them using a range comparison
SELECT * FROM t WHERE val1 >= 100 AND val1 < 200
Similarly for 19x.xx values, make it >= 190
Avoid converting data wherever possible; it adds overhead which affects query performance, and also means that indexes cannot be used - this can massively impact the performance of a query
You can simply use LIKE % conditioning when filtering results you selct from the table and so it goes like this.
SELECT * FROM TABLE_NAME WHERE STR(VAL1, 10, 5) LIKE '19%'
This works for me whenever I select a row containing a specific char or number of a column containing value.
EDIT: Used STR() function to convert numeric data into character data.
Use like operator to get your results. No need to convert datatype of Val1.
rows where val1 starts with 1:
SELECT * FROM T WHERE val1 LIKE '1%';
rows where val1 starts with 19:
SELECT * FROM T WHERE val1 LIKE '19%';
This question already has many good answers, below answer is a different approach.
create table table1(
id char(10),
val float
);
insert into table1 values('a',199.87);
insert into table1 values('b',166.56);
insert into table1 values('c',100.67);
insert into table1 values('d',233.45);
insert into table1 values('e',177.23);
Query
select * from table1 where (CHARINDEX( '1',val, 1))=1;
select * from table1 where (CHARINDEX( '19',val, 1))=1;
output
id val
a 199,87
b 166,56
c 100,67
e 177,23
id val
a 199,87
Related
Let's say, I have a table from log, it looks like this:
Log Table
I need a result table like:
Result table
But the problem is my dataset is not only 7, but maybe 24, 100 value columns.
My query with 7 value columns is:
select
*
from My_Dataset
unpivot
(status for value in (value_1, value_2, value_3, value_4, value_5, value_6, value_7))```
But is there anyway to automatic this process for value_n?
Thank you.
Consider below approach
select id, arr[offset(1)] as value
from your_table t,
unnest(split(translate(to_json_string(t), '{}"', ''))) kv,
unnest([struct(split(kv, ':') as arr)])
where starts_with(arr[offset(0)], 'value_')
if applied to sample data in your question (i used only three value_N columns but it works for any!)
Another option (maybe less verbose and simpler to swallow)
select id, val
from your_table t, unnest([to_json_string(t)]) json,
unnest(`bqutil.fn.json_extract_keys`(json)) col with offset
join unnest(`bqutil.fn.json_extract_values`(json)) val with offset
using(offset)
where starts_with(col, 'value_')
obviously with same output as above first option
It's possible via SQL scripting.
You have to get a column list of your table first and save it in variable. Then call dynamic query with EXECUTE IMMEDIATE
DECLARE field_list STRING;
SET field_list = ((
SELECT STRING_AGG(column_name) FROM `my_project_id`.my_dataset.INFORMATION_SCHEMA.COLUMNS
WHERE column_name LIKE "value_%" AND table_name = 'my_table'
));
EXECUTE IMMEDIATE "SELECT id, SPLIT(value, '_')[OFFSET(1)] value FROM my_dataset.my_table UNPIVOT (status FOR value IN ("||field_list||"))"
I am trying to formulate a query that will allow me to find all records from a single column with 3 hyphens. An example of a record would be like XXXX-RP-XXXAS1-P.
I need to be able to sort through 1000s of records with either 2 or 3 hyphens.
You can REPLACE the hyphens in the string with an empty string and compute the difference of the length of original string and the replaced string to check for the number of hyphens.
select *
from yourtable
where len(column_name)-len(replace(column_name,'-',''))=3
and substring(column_name,9,1) not like '%[0-9]%'
If your records have 2 or 3 hyphens, then just do:
where col like '%-%-%-%'
This will get 3 or more hyphens. For exactly 3:
where col like '%-%-%-%' and col not like '%-%-%-%-%'
try this,
declare #t table(col1 varchar(50))
insert into #t values ('A-B'),('A-B-C-D-E'),('A-B-C-D')
select * from
(SELECT *
,(len(col1) - len(replace(col1, '-', ''))
/ len('-')) col2
FROM #T)t4
where col2=3
I am working on a Microsoft SQL Server database and I have the following problem to implement these 2 simple select query.
So I have a table named MyTable that has a column OtherFieldFK of type BigInt with a value of 70016592107.
So for example I want search all the record in this table that have the OtherFieldFK starting with the value 70.
I tried to use like in this way:
select *
from MyTable
where OtherFieldFK like = '70%'
but it doesn't work. I think that like clause works only on string, is it right?
In this table I also have a DATETIME column named DataInizioGestione.
I tried to do the same thing:
select *
from DataInizioGestione
where OtherFieldFK like = '2016%'
but in this case it doesn't work either.
How can I correctly implement these 2 queries?
the first should be right, as you wrote:
select * from MyTable where OtherFieldFK like = '70%'
for the second should be converted to the date format in the nvarchar (es 121 with this format aaaa-mm-gg hh:mi:ss.mmm(24h)); in this way you can make the comparison with the like:
select * from MyTable where convert(nvarchar,DataInizioGestione,121) like = '2016%'
or you can directly compare the year:
select * from MyTable where year(DataInizioGestione) = 2016
Example,
Suppose I have following column values as in column1 in three rows,
10,9,2,3
12,9,8,9
16,2,9,2
I need to get the records based on column1 value with 2nd position value to be 9.
Result I am expecting as follows,
10,9,2,3
12,9,8,9
Thanks
Rajasekar R
Try Regex
select * from a where a1 ~ '^\d+[,][9][,]';
or
select * from a where a1 ~ '^\d+,9,';
Both work flawlessly
For Input
ABC
DEF
HIJ
1,9,2,3
5,9,4,6
1,2,3,9
2,3,3,9
5,99,4,6
10,9,2,3
12,9,8,9
16,2,9,2
162,9,2
Output
1,9,2,3
5,9,4,6
10,9,2,3
12,9,8,9
162,9,2
I am having Postgres So I used ~ , for others you can use respective regex command
You can try above example (SQL) for your case :
DECLARE #tempTable TABLE(Value NVARCHAR(100))
INSERT INTO #tempTable VALUES('10,9,2,3');
INSERT INTO #tempTable VALUES('12,9,8,9');
INSERT INTO #tempTable VALUES('16,2,9,2');
SELECT *
FROM #tempTable
WHERE SUBSTRING(Value,CHARINDEX(',', Value)+1,1) = '9'
I have a table column that has data like
NA_PTR_51000_LAT_CO-BOGOTA_S_A
NA_PTR_51000_LAT_COL_M_A
NA_PTR_51000_LAT_COL_S_A
NA_PTR_51000_LAT_COL_S_B
NA_PTR_51000_LAT_MX-MC_L_A
NA_PTR_51000_LAT_MX-MTY_M_A
I want to parse each column value so that I get the values in column_B. Thank you.
COLUMN_A COLUMN_B
NA_PTR_51000_LAT_CO-BOGOTA_S_A CO-BOGOTA
NA_PTR_51000_LAT_COL_M_A COL
NA_PTR_51000_LAT_COL_S_A COL
NA_PTR_51000_LAT_COL_S_B COL
NA_PTR_51000_LAT_MX-MC_L_A MX-MC
NA_PTR_51000_LAT_MX-MTY_M_A MX-MTY
I'm not sure of the Postgresql and I can't get SQL fiddle to accept the schema build...
substring and length may vary...
Select Column_A, substr(columN_A,18,length(columN_A)-17-4) from tableName
Ok how about this then:
http://sqlfiddle.com/#!15/ad0dd/56/0
Select column_A, b
from (
Select Column_A, b, row_number() OVER (ORDER BY column_A) AS k
FROM (
SELECT Column_A
, regexp_split_to_table(Column_A, '_') b
FROM test
) I
) X
Where k%7=5
Inside out:
Inner most select simply splits the data into multiple rows on _
middle select adds a row number so that we can use the use the mod operator to find all occurances of a 5th remainder.
This ASSUMES that the section of data you're after is always the 5th segment AND that there are always 7 segments...
Use regexp_matches() with a search pattern like 'NA_PTR_51000_LAT_(.+)_'
This should return everything after NA_PTR_51000_LAT_ before the next underscore, which would match the pattern you are looking for.