Generate series for various mixes of numbers and letteres - postgresql

I am using this syntax:
generate_series(1, COALESCE((string_to_array(table.id_number, '-')) [2] :: INT, 1)) AS n (numbers)
To generate IDs in elements that have got ID like 32.22.1-4 to get 4 rows with IDs 32.22.1, 32.22.2, 32.22.3 and 32.22.4. How to change it to accept also letters?
So for 32.22.a-c there would be:
32.22.a, 32.22.b, 32.22.c
And for 32.22.d1-d4 there would be
32.22.d1, 32.22.d2, 32.22.d3, 32.22.d4
EDIT:
The whole code looks like:
INSERT INTO ...
(
SELECT
...
FROM table
CROSS JOIN LATERAL
generate_series(1, COALESCE((string_to_array(table.id_number, '-')) [2] :: INT, 1)) AS n (numbers)
WHERE table.id_number LIKE ...
);

WITH t(id_number) AS ( VALUES
('32.33.a1-a5'::TEXT),
('32.34.a-c'::TEXT),
('32.35.b-e'::TEXT)
), stats AS (
SELECT
chars,
chars[1] pattern, -- pattern use
CASE
WHEN (ascii(chars[3]) - ascii(chars[2])) = 0
THEN FALSE
ELSE TRUE
END char_pattern, -- check if series of chars
CASE
WHEN (ascii(chars[3]) - ascii(chars [2])) = 0
THEN right(chars[3],1)::INTEGER
ELSE (ascii(chars[3]) + 1 - ascii(chars[2]))::INTEGER
END i -- number of series
FROM t,
regexp_matches(t.id_number, '(.*\.)(\w*)-(\w*)$') chars
)
SELECT
CASE WHEN char_pattern
THEN pattern || chr(ascii(chars[2]) - 1 + s)
ELSE pattern || left(chars[2],1) || s::TEXT
END output
FROM stats,generate_series(1,stats.i) s;
Result:
output
---------
32.33.a1
32.33.a2
32.33.a3
32.33.a4
32.33.a5
32.34.a
32.34.b
32.34.c
32.35.b
32.35.c
32.35.d
32.35.e
(12 rows)

Related

convert actual string and characters to numbers in PostgreSQL

Is there a way i could convert an actual string to a number in postgresql
i have record stored in db and below is an example of unique identifier found in each record.
d895774d-7b91-4adc-bfba-f1264e5aae04
I want to store this record in another database but i would want to generate another unique number for each transaction/line
Is there a way i can convert this d895774d-7b91-4adc-bfba-f1264e5aae04 to some number.
like this actual numbers 13693660123082308270370273012321321312321
select 'd895774d-7b91-4adc-bfba-f1264e5aae04' as id
First convert the string into a table of single characters (the from clause);
Then select the digits 'as is', a as 10, b as 11 and so on (the case expression);
Finally aggregate into a string (string_agg)
skipping the - characters (where clause).
select
string_agg(case when c between '0' and '9' then c else (ascii(c) - 87)::text end, '')
from unnest(string_to_array('d895774d-7b91-4adc-bfba-f1264e5aae04', null)) c
where c <> '-';
Result: 13895774137119141013121115111015126414510101404
Edit
select
td.date,
(
select string_agg(case when c between '0' and '9' then c else (ascii(c) - 87)::text end, '')
from unnest(string_to_array(td.id, null)) c
where c <> '-'
) as id
from table_d td;

replace elements in a 2d array

Given a 2d array
select (ARRAY[[1,2,3], [4,0,0], [7,8,9]]);
{{1,2,3},{4,0,0},{7,8,9}}
Is there a way to replace the slice at [2:2][2:] (the {{0,0}}) with values 5 and 6? array_replace replaces a specific value so I'm not sure how to approach this.
I believe it's more readable to code a function in plpgsql. However, a pure SQL solution also exists:
select (
select array_agg(inner_array order by outer_index)
from (
select outer_index,
array_agg(
case
when outer_index = 2 and inner_index = 2 then 5
when outer_index = 2 and inner_index = 3 then 6
else item
end
order by inner_index
) inner_array
from (
select item,
1 + (n - 1) % array_length(a, 1) inner_index,
1 + (n - 1) / array_length(a, 2) outer_index
from
unnest(a) with ordinality x (item, n)
) _
group by outer_index
)_
)
from (
select (ARRAY[[1,2,3], [4,0,0], [7,8,9]]) a
)_;

TSQL GROUP BY part of string

I have a simple query. Something like this:
SELECT l.list_name, COUNT(order_id)
FROM orders o JOIN lists l ON l.order_id=o.order_id
WHERE l.list_name LIKE 'orders_1%' or l.list_name LIKE 'orders_2%'
GROUP BY l.list_name
The situation looks like this: overight a stored procedure is updating the lists table, but it chops lists in parts if there are more than 1000 orders.
If I have 1200 orders with criteria or list 'orders_1', then my procedure will create two lists: 'orders_1_1' 'and orders_1_2', the first having 1,000 and second 200 orders.
So when I run my query to count those orders I will get results like so:
list_name count
orders_1 100
orders_1_more_than_100_1 1000
orders_1_more_than_100_2 200
orders_2 400
orders_3_1 1000
orders_3_2 1000
orders_3_3 420
orders_3_more_than_100_1 1000
orders_3_more_than_100_2 900
orders_3_more_than_200_1 1000
orders_3_more_than_200_2 1000
orders_3_more_than_200_3 100
orders_4 200
orders_4_more_than_300 200
The result I would like to get should look like this:
list_name count
orders_1 100
orders_1_more_than_100 1200
orders_2 400
orders_3 2420
orders_3_more_than_100 1900
orders_3_more_than_200 2100
orders_4 200
orders_4_more_than_300 200
So that it will sum all lists that start the same.
Any ideas on that? :)
These are the exact values that I have in my list_names column:
WYS_AUT_PISMO_NR_6
WYS_AUT_PISMO_NR_5_POWYZEJ_240
WYS_AUT_PISMO_NR_5_DO_240
WYS_AUT_PISMO_NR_4_POWYZEJ_240_5
WYS_AUT_PISMO_NR_4_POWYZEJ_240_4
WYS_AUT_PISMO_NR_4_POWYZEJ_240_3
WYS_AUT_PISMO_NR_4_POWYZEJ_240_2
WYS_AUT_PISMO_NR_4_POWYZEJ_240_1
WYS_AUT_PISMO_NR_4_DO_240
WYS_AUT_PISMO_NR_3_POWYZEJ_240
WYS_AUT_PISMO_NR_3_DO_240
WYS_AUT_PISMO_NR_2_POWYZEJ_240
WYS_AUT_PISMO_NR_2_DO_240
WYS_AUT_PISMO_NR_1
What I want is to group them like so:
WYS_AUT_PISMO_NR_6
WYS_AUT_PISMO_NR_5_POWYZEJ_240
WYS_AUT_PISMO_NR_5_DO_240
WYS_AUT_PISMO_NR_4_POWYZEJ_240 /*here I must group those 5 lists*/
WYS_AUT_PISMO_NR_4_DO_240
WYS_AUT_PISMO_NR_3_POWYZEJ_240
WYS_AUT_PISMO_NR_3_DO_240
WYS_AUT_PISMO_NR_2_POWYZEJ_240
WYS_AUT_PISMO_NR_2_DO_240
WYS_AUT_PISMO_NR_1
This monstruous expression will isolate string starting from beginning of parameter to last _ if there are more than one underscores:
select case when len (l.list_name) - len (replace (l.list_name, '_', '')) > 1
then left(l.list_name,
len (l.list_name) - charindex('_', reverse(l.list_name)))
else l.list_name
end
Alternatively you might strip 'orders_' from string, replace underscore with dot and convert it to float, then to int to remove decimals, and then back to string using this monstrosity:
select 'orders_' + cast (cast (cast (
replace (substring (#str, 8, 100), '_', '.')
as float) as int) as varchar(100))
To avoid repeating this blobs, use derived table instead of lists:
SELECT l.TrimmedListName, COUNT(order_id)
FROM orders o
JOIN
(
select lists.*,
-- Remove optional list continuation number
case when len (list_name) - len (replace (list_name, '_', '')) > 1
then left(list_name,
len (list_name) - charindex('_', reverse(list_name)))
else list_name
end AS TrimmedListName
from lists
) l ON l.order_id=o.order_id
WHERE (l.list_name LIKE 'orders_1%' or l.list_name LIKE 'orders_2%')
GROUP BY l.TrimmedListName
try something like
select substring(l.list_name, 0, 8), count(order_Id)
FROM orders o JOIN lists l ON l.order_id=o.order_id
WHERE l.list_name LIKE 'orders_1%' or l.list_name LIKE 'orders_2%'
group by substring(l.list_name, 0, 8)
Updated answer for the updated question:
select newColName, COUNT(order_id)
from
(
select case when GetSubstringCount(l.list_name, '_', '') > 1 then
SUBSTRING(l.list_name, 0, len(l.list_name) - 2)
else l.list_name end as NewColName
, order_Id
FROM orders o JOIN lists l ON l.order_id=o.order_id
WHERE l.list_name LIKE 'orders_1%' or l.list_name LIKE 'orders_2%'
) mySubTable
group by newColName
You'll need something like This to create the GetSubstringCount method

T-SQL: How to obtain the exact length of a string in characters?

I'm generating T-SQL SELECT statements for tables for which I have no data type information up-front. In these statements, I need to perform string manipulation operations that depend on the length of the original value of the tables' columns.
One example (but not the only one) is to insert some text at a specific position in a string, including the option to insert it at the end:
SELECT
CASE WHEN (LEN ([t0].[Product] = 8)
THEN [t0].[Product] + 'test'
ELSE STUFF ([t0].[Product], 8, 0, 'test')
END
FROM [OrderItem] [t0]
(The CASE WHEN + LEN is required because STUFF doesn't allow me to insert text at the end of a string.)
The problem is that LEN excludes trailing blanks, which will ruin the calculation.
I know I can use DATALENGTH, which does not exclude trailing blanks, but I can't convert the bytes returned by DATALENGTH to the characters required by STUFF because I don't know whether the Product column is of type varchar or nvarchar.
So, how can I generate a SQL statement that depends on the exact length of a string in characters without up-front information about the string data type being used?
Here's what I ended up using:
SELECT
CASE WHEN ((LEN ([t0].[Product] + '#') - 1) = 8)
THEN [t0].[Product] + 'test'
ELSE STUFF ([t0].[Product], 8, 0, 'test')
END
FROM [OrderItem] [t0]
Measurements indicate that the LEN (... + '#') - 1 trick is about the same speed as LEN (...) alone.
Thanks for all the good answers!
try this:
SELECT
CASE WHEN (LEN (REPLACE([t0].[Product],' ', '#') = 8)
THEN [t0].[Product] + 'test'
ELSE STUFF ([t0].[Product], 8, 0, 'test')
END
FROM [OrderItem] [t0]
Can't you look up the type information for the columns in the system tables?
If not then to determine whether or not a column is varchar or nvarchar this would do it.
create table #test
(
c varchar(50),
n nvarchar(50)
)
insert into #test values ('1,2,3,4 ',N'1,2,3,4,5 ')
SELECT
CASE
WHEN datalength(CAST(c AS nvarchar(MAX))) = datalength(c)
THEN 'c is nvarchar'
ELSE 'c is char'
END,
CASE
WHEN datalength(CAST(n AS nvarchar(MAX))) = datalength(n)
THEN 'n is nvarchar'
ELSE 'n is char'
END
FROM #test
Use DATALENGTH and SQL_VARIANT_PROPERTY:
SELECT
CASE
WHEN 8
= DATALENGTH([t0].[Product])
/ CASE SQL_VARIANT_PROPERTY([t0].[Product],'BaseType') WHEN 'nvarchar' THEN 2 ELSE 1 END
THEN [t0].[Product] + 'test'
ELSE STUFF ([t0].[Product], 8, 0, 'test')
END
FROM [OrderItem] [t0]
If there are no leading blanks, len(reverse(column_name)) will give you the column length.

How to conditionally filter on a column in a WHERE clause?

OK, the umpteenth conditional column question:
I'm writing a stored proc that takes an input parameter that's mapped to one of several flag columns. What's the best way to filter on the requested column? I'm currently on SQL2000, but about to move to SQL2008, so I'll take a contemporary solution if one's available.
The table queried in the sproc looks like
ID ... fooFlag barFlag bazFlag quuxFlag
-- ------- ------- ------- --------
01 1 0 0 1
02 0 1 0 0
03 0 0 1 1
04 1 0 0 0
and I want to do something like
select ID, name, description, ...
from myTable
where (colname like #flag + 'Flag') = 1
so if I call the sproc like exec uspMyProc #flag = 'foo' I'd get back rows 1 and 4.
I know I can't do the part in parens directly in SQL. In order to do dynamic SQL, I'll have to stuff the entire query into a string, concatenate the #flag param in the WHERE clause and then exec the string. Aside from the dirty feeling I get when doing dynamic SQL, my query is fairly large (I'm selecting a couple dozen fields, joining 5 tables, calling a couple of functions), so it's a big giant string all because of a single line in a 3-line WHERE filter.
Alternately, I could have 4 copies of the query and select among them in a CASE statement. This leaves the SQL code directly executable (and subject to syntax hilighting, etc.) but at the cost of repeating big chunks of code, since I can't use the CASE on just the WHERE clause.
Are there any other options? Any tricky joins or logical operations that can be applied? Or should I just get over it and exec the dynamic SQL?
There are a few ways to do this:
You can do this with a case statement.
select ID, name, description, ...
from myTable
where CASE
WHEN #flag = 'foo' then fooFlag
WHEN #flag = 'bar' then barFlag
END = 1
You can use IF.
IF (#flag = 'foo') BEGIN
select ID, name, description, ...
from myTable
where fooFlag = 1
END ELSE IF (#flag = 'bar') BEGIN
select ID, name, description, ...
from myTable
where barFlag = 1
END
....
You can have a complicated where clause with a lot of parentheses.
select ID, name, description, ...
from myTable
where (#flag = 'foo' and fooFlag = 1)
OR (#flag = 'bar' and barFlag = 1) OR ...
You can do this with dynamic sql:
DECLARE #SQL nvarchar(4000)
SELECT #SQL = N'select ID, name, description, ...
from myTable
where (colname like ''' + #flag + 'Flag'') = 1'
EXECUTE sp_ExecuteSQL #SQL, N''
There are more, but I think one of these will get you going.
"Alternately, I could have 4 copies of the query and select among them in a CASE statement."
You don't need to copy your entire query 4 times, just add all the possibilities into the where clauses in your single copy of the query:
select ID, name, description, ...
from myTable
where (#flag = 'foo' and fooFlag = 1) OR (#flag = 'bar' and barFlag = 1) OR ...
What I would do is CASE some variables at the beginning. Example:
DECLARE
#fooFlag int,
#barFlag int,
#bazFlag int,
#quuxFlag int
SET #fooFlag = CASE WHEN #flag = 'foo' THEN 1 ELSE NULL END
SET #barFlag = CASE WHEN #flag = 'bar' THEN 1 ELSE NULL END
SET #bazFlag = CASE WHEN #flag = 'baz' THEN 1 ELSE NULL END
SET #quuxFlag = CASE WHEN #flag = 'quux' THEN 1 ELSE NULL END
SELECT ID, name, description, ...
FROM myTable
WHERE (fooFlag >= ISNULL(#fooFlag, 0) AND fooFlag <= ISNULL(#fooFlag, 1))
AND (barFlag >= ISNULL(#barFlag, 0) AND barFlag <= ISNULL(#barFlag, 1))
AND (bazFlag >= ISNULL(#bazFlag, 0) AND bazFlag <= ISNULL(#bazFlag, 1))
AND (quuxFlag >= ISNULL(#quuxFlag, 0) AND quuxFlag <= ISNULL(#quuxFlag, 1))
The good thing about this query is that, because the possible values for "flags" are bounded, you can calculate all your conditionals as prerequisites instead of wrapping columns in them. This guarantees a high-performance index seek on whichever columns are indexed, and doesn't require writing any dynamic SQL. And it's better than writing 4 separate queries for obvious reasons.
You could have a parameter for each possible flag column, then check if the parameter is null or the value in the column is equal to the parameter. Then you pass in a 1 for the flags that you want to check and leave the others null.
select id, name, description, ...
from myTable
where (#fooFlag is null or fooFlag = #fooFlag) AND
(#barFlag is null or barFlag = #barFlag) AND
...
Honestly, though, this seems like an ideal candidate for building a dynamic LINQ query and skipping the SPROC once you get to SQL2008.
int should be accepted as varchar value
declare #CompanyID as varchar(10) = '' -- or anyother value
select * from EmployeeChatTbl chat
where chat.ConversationDetails like '%'+#searchKey+'%'
and
(
(0 = CASE WHEN (#CompanyID = '' ) THEN 0 ELSE 1 END)
or
(chat.CompanyID = #CompanyID)
)
working
when the companyID is present , then filtration based on it is done, other wise , filtration is skipped.
where
case when #value<>0 then Field else 1 end
=
case when #value<>0 then #value else 1 end