Select a string from a specific place - T-SQl [duplicate] - sql

This question already has answers here:
T-SQL Find char string and take all char to right of expression
(3 answers)
Closed 8 years ago.
Let's say I have following records in my table.
4 - Mar 1 thru Apr 11
13 - Dec 01 thru Dec 31
I want to select the string so that the output would be,
Mar 1 thru Apr 11
Dec 01 thru Dec 31
How can I do that?
Thank you

I could use:
CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] )
See for documentation: http://msdn.microsoft.com/en-us/library/ms186323.aspx
So, this will be:
SELECT SUBSTRING([*FieldName*], CHARINDEX('-', [*FieldName*])+2, 252) FROM [*Table*]
252 is the number of characters, and that's the default length of nvarchar fields. Increase it or decrease this number if need be.
I put +2 to strip out the - (dash and white space).

You have a lot of choices, I will use SELECT with SUBSTR and LEN clause, (see this page: http://oreilly.com/catalog/sqlnut/chapter/ch04.html)
Data:
4 - Mar 1 thru Apr 11
13 - Dec 01 thru Dec 31
SELECT SUBSTR(your-field,4,TRIM(LEN(your-field)-4)) FROM your-table;
OUTPUT:
Mar 1 thru Apr 11
Dec 01 thru Dec 31
NOTES
- SUBSTR: return part of argument
- LEN: return lenght of argument
- TRIM: return lenght without spaces

SELECT REPLACE((SUBSTRING('4 - Mar 1 thru Apr 11', CHARINDEX(' - ', '4 - Mar 1 thru Apr 11'), LEN('4 - Mar 1 thru Apr 11'))),' - ','')
This also works,
I will check out your option now.
Thank you for all your help guys.

Related

Subtraction of inventory from Demand in BigQuery everday and adding new inventory

Here's how my data looks like:
date
sku
inventory_added
demand
22nd Nov 2021
XYZ
70
18
23rd Nov 2021
XYZ
0
18
24th Nov 2021
XYZ
0
50
25th Nov 2021
XYZ
0
15
26th Nov 2021
XYZ
80
30
27th Nov 2021
XYZ
0
20
28th Nov 2021
XYZ
0
15
29th Nov 2021
XYZ
0
20
30th Nov 2021
XYZ
0
10
1st Dec 2021
XYZ
100
40
2nd Dec 2021
XYZ
0
10
I want to create a new column named solution using BigQuery SQL where in the 1st row, i.e. 22nd Nov 2021, I want formula as - inventory_added - demand.
This will give me 1st row's value for solution will be 52.
Now what I am not able to do is from 2nd row:
So, next now, will be 52 (remaining inventory from previous day) + 0 (inventory_added on 23rd Nov 2021) - 18 (demand on 23 Nov 2021). This is equal to 34.
Similarly going to next row, i.e. 24th November:
value in solution will be 34 + 0 - 50 = -16. Now since it is negative, it should be put as 0.
I tried this - MAX(solutions, 0).
The result will look like this:
date
sku
inventory_added
demand
solution
22nd Nov 2021
XYZ
70
18
52
23rd Nov 2021
XYZ
0
18
34
24th Nov 2021
XYZ
0
50
0
25th Nov 2021
XYZ
0
15
0
26th Nov 2021
XYZ
80
30
50
27th Nov 2021
XYZ
0
20
30
28th Nov 2021
XYZ
0
15
15
29th Nov 2021
XYZ
0
20
0
30th Nov 2021
XYZ
0
10
0
1st Dec 2021
XYZ
100
40
60
2nd Dec 2021
XYZ
0
10
50
I am not sure if this can be accomplished by BigQuery, but all suggestions are welcome.
Thanks!
Without the condition "it is negative, it should be put as 0" you may use window (in BigQuery terms - analytic) variant of SUM() function:
SELECT *,
SUM(inventory_added - demand) OVER (PARTITION BY sku ORDER BY date) AS solution
FROM source_table
With this condition the output become iterative, and you must use recursive CTE (if available in BigQuery) or iterative stored procedure.
I see that recursive CTE is not available in BigQuery ... Can you provide a pseudo code may as a starting point for stored procedures? – Shantanu Jain
CREATE PROCEDURE procname()
BEGIN
CREATE temptable;
OPEN CURSOR FOR SELECT * FROM datatable ORDER BY date;
SET #solution = 0;
FETCH CURSOR INTO #date, #sku, #inventory_added, #demand;
LOOP ​
​ SET #solution = GREATEST(#solution + #inventory_added - #demand, 0);
​ INSERT INTO temptable VALUES (#date, #sku, #inventory_added, #demand, #solution);
FETCH CURSOR INTO #date, #sku, #inventory_added, #demand;
UNTIL NO_ROWS_IN_CURSOR END LOOP;
SELECT * FROM temptable;
DROP temptable;
END
AS an option - consider use of recently introduced FOR...IN Loop
declare result int64;
declare prev_sku string;
create temp table results as (select *, 0 as solution from your_table where false);
set (result, prev_sku) = (0, '');
for record in (select *, parse_date('%d %B %Y', regexp_replace(date, r'(\d*)(\w*)( \w{3} \d{4})', r'\1 \3')) dt from your_table order by sku, dt) do
if record.sku != prev_sku then set result = 0; end if;
set result = result + record.inventory_added - record.demand;
if result < 0 then set result = 0; end if;
insert into results values(record.date, record.sku, record.inventory_added, record.demand, result);
set prev_sku = record.sku;
end for;
select * from results
order by sku, parse_date('%d %B %Y', regexp_replace(date, r'(\d*)(\w*)( \w{3} \d{4})', r'\1 \3'));
If applied to sample data in your question - output is
Note: While delivering expected result - obviously this is going to be extremely slow (as any cursor based solution) - so while applicable for learning - I don't think appropriate for real production use

Sort String Value for Date in SQL

I have an issue as I am trying to select Date values stored in SQL server as String value with this format "Thu, 08 Jul 2021 06:08:20 -0700" and i need to select all table with newest date in first but I do not know how to convert this String into Date and sort it. Thanks in advance.
Table
|Thu, 08 Jul 2021 06:08:20 -0700|
|Fri, 09 Jul 2021 01:08:20 -0700|
|Sun, 11 Jul 2021 07:08:20 -0700|
output (Newest Date first)
|Sun, 11 Jul 2021 07:08:20 -0700|
|Fri, 09 Jul 2021 01:08:20 -0700|
|Thu, 08 Jul 2021 06:08:20 -0700|
Your date is just missing a valid timezone offset value so needs a ":" inserted so it's -07:00, you can do this with stuff and use substring to ignore the irrelevant day name. You don't state a specific database platform, for SQL Server you can then cast to a datetimeoffset, other databases have similar but slightly varied syntax. This assumes the strings are all formatted consistently of course.
declare #d varchar(30)='Thu, 08 Jul 2021 06:08:20 -0700'
select Cast(Stuff(Substring(#d,6,26),25,0,':') as datetimeoffset(0))
Result
2021-07-08 06:08:20 -07:00

How to extract dates from string fields in SQL?

I have field that contains strings and has dates within.
e.g
Rate (20 Jan 2020 - 19 Feb 2020)
or Rate (6 Dec 2019 - 5 Jan 2020)
I need a Start Date and End Date out of the above strings in SQL.
I can get Start Date but End Date (after the -) is a problem
Its quite crude but it will get you answers:
select left('20 Jan 2020 - 19 Feb 2020',CHARINDEX('-','20 Jan 2020 - 19 Feb 2020')-1)
,right('20 Jan 2020 - 19 Feb 2020',len('20 Jan 2020 - 19 Feb 2020') -CHARINDEX('-','20 Jan 2020 - 19 Feb 2020')-1)
CHARINDEX() will give you the position of the character you desire, in this case the dash. From there you can use LEFT(), RIGHT(), and LEN() to get the pieces out of the string that you need.
This works with SQLServer

Extract Date from varchar field in SQL Server 2008

I have a table which has only 1 large column named Details; each record looks similar to this:
Record#1: ...ID: <klsdhf89435> Date: 1 Jun 2011 12:28:14 From: "Yahoo"...
Record#2: ...Subject: test Date: Fri, 24 May 2010 13:18:43 -0500 ID: <7532432423>...
Record#3: ...ID: <234321fd> Date: 14 Jun 2010 12:28:14 From: "Gmail"...
Record#4: ...ID: <12434> Date: 1 Jun 2011 12:28:14 From: "Yahoo"...
I would like the subtract the Date only. So, for those 4 records, I would like to extract:
1 Jun 2011 12:28:14
Fri, 24 May 2010 13:18:43 -0500
14 Jun 2010 12:28:14
1 Jun 2011 12:28:14
Please note that the double space from before "From" or before "ID" is a new line character which is Char(10) in SQL Server.
Thanks in advance
SELECT SUBSTR(Details, LOCATE('Date: ', Details), LOCATE(' From:', Details) - LOCATE('Date: ', Details))
FROM TABLENAME
Consider parsing the date into a new date column when the row is inserted.
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

Trying to pull the required rows from the single table with applying conditional statements on columns in sql server?

I have tried in n-number ways to solve this solution but unfortunately I got stuck in all the ways..
source table
id year jan feb mar apr may jun jul aug sep oct nov dec
1234 2014 05 06 12 15 16 17 18 19 20 21 22 23
1234 2013 05 06 12 15 16 17 18 19 20 21 22 23
Task: Assume that we are currently at March 2014, and we need 12 months back date ...(i.e., from Mar 2013 to Feb 2014, and the remaining values needs to be zero except year and id.)
Solution:
id year jan feb mar apr may jun jul aug sep oct nov dec
1234 2014 05 06 0 0 0 0 0 0 0 0 0 0
1234 2013 0 0 12 15 16 17 18 19 20 21 22 23
This needs a code solution for SQL Server 2008. I would be very happy if any body can solve this.
Note:
I got stuck to pull the column names dynamically.
You can try this:
select id, year, case when DATEDiff(month, getdate(), convert(datetime, year + '-01-01'))) < 12 then jan else 0,
DATEDiff(month, getdate(), convert(datetime, year + '-02-01'))) < 12 then fab else 0 ....