How can I find the last member of an array in PostgreSQL? - sql

How can I find the last member of an array in PostgreSQL?
for example you have an array of the numbers which each of them are id of a course, in the list of your chosen courses I want to know the last one : [1,32,4,6] I need number 6 ! how can I find the last number which is 6 ?

You can use array function array_upper() to get the index of the last element.
Consider:
with t as (select '{1,32,4,6}'::int[] a)
select a[array_upper(a, 1)] last_element from t
Demo on DB Fiddle:
| last_element |
| -----------: |
| 6 |

You can use ARRAY_UPPER to get the upper bound of your array. You can then retrieve the value at that returned index.
SELECT yourcolumn[ARRAY_UPPER(yourcolumn,1)] FROM yourtable;

Related

Athena query get the index of any element in a list

I need to access to the elements in a column whose type is list according to the other elements' locations in another list-like column. Say, my dataset is like:
WITH dataset AS (
SELECT ARRAY ['hello', 'amazon', 'athena'] AS words,
ARRAY ['john', 'tom', 'dave'] AS names
)
SELECT * FROM dataset
And I'm going to achieve
SELECT element_at(words, index(names, 'john')) AS john_word
FROM dataset
Is there a way to have a function in Athena like "index"? Or how can I customize one like this? The desired result should be like:
| -------- |
| john_word|
| -------- |
| hello |
| -------- |
array_position:
array_position(x, element) → bigint
Returns the position of the first occurrence of the element in array x (or 0 if not found).
Note that in presto array indexes start from 1.
SELECT element_at(words, array_position(names, 'john')) AS john_word
FROM dataset

Count the number of occurences of a key in a json object - IMPALA/HIVE

I have a column in my Impala Table which is a map<string,string>. I have extracted that column as a key and value pair in 2 different cols as shown below.
The value column is a json object. I have to find out whether there are multiple occurrences of a particular key in that value column for a particular id.
id | key | value
1 | brm_res | {'abc':'3rr','vbg':''r45','abc':'5rr'}
2 | brm_res | {'abc':'3rr','vbg':''r45','bgh':'5rr'}
3 | brm_res | {'abc':'3rr','vbg':''r45','tyu':'5rr'}
4 | brm_res | {'abc':'3rr','vbg':''r45','yuo':'5rr'}
As shown in the example above, for a particular id(id=1) and key(brm_res), there are 2 entries for (abc) key in the value column. How to find this.
Please guide. Thanks in advance.
You can calculate character length of initial string, remove all occurences of key, calculate the difference in length, divide by length of key, it will be the number of occurrences. Something like this (not tested):
(char_length(value)-char_length(replace(value, "\'abc\':", ''))) div char_length("\'abc\':");

SQL How do I get a part of a value that is between between specific left and right value

I would like to know what select statement can be used to get a piece of a column value that is between a specific value on the right and on the left.
Table contains the following information.
shipment_plsid
tag
element
1948
INCOTERMS
INCOTERMS VER="1">TYP>4/TYP>VAR>SHIPPER/VAR>/INCOTERMS>
2023
INCOTERMS
INCOTERMS VER="1">TYP>4/TYP>VAR>DDP/VAR>/INCOTERMS>
I need to retrieve the value for all records from column element that is between VAR> and /VAR.
Result should look like:
element
SHIPPER
DDP
Thanks
If you are using MySQL, this is what you need:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('VER="1">TYP>4/TYP>VAR>SHIPPER</VAR</INCOTERMS', "</VAR", 1), "VAR>", -1);
For example:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('VER="1">TYP>4/TYP>VAR>SHIPPER</VAR</INCOTERMS', "</VAR", 1), "VAR>", -1) as result;
+----------+
| result |
|----------|
| SHIPPER |
+----------+
1 row in set
Time: 0.011s
If you are using another db, please let us know which one it is
Use a SUBSTRING function and work out the start/length using CHARINDEX.
You have to add four characters to your first parameter to move start position to the end of the VAR> phrase. Similarly work out the length.
Here is a working solution:
select SUBSTRING(element,CHARINDEX('VAR>',element)+4,CHARINDEX('/VAR>',element)-CHARINDEX('VAR>',element)-4)from YourTable

In Postgres: Select columns from a set of arrays of columns and check a condition on all of them

I have a table like this:
I want to perform count on different set of columns (all subsets where there is at least one element from X and one element from Y). How can I do that in Postgres?
For example, I may have {x1,x2,y3}, {x4,y1,y2,y3},etc. I want to count number of "id"s having 1 in each set. So for the first set:
SELECT COUNT(id) FROM table WHERE x1=1 AND x2=1 AND x3=1;
and for the second set does the same:
SELECT COUNT(id) FROM table WHERE x4=1 AND y1=1 AND y2=1 AND y3=1;
Is it possible to write a loop that goes over all these sets and query the table accordingly? The array will have more than 10000 sets, so it cannot be done manually.
You should be able convert the table columns to an array using ARRAY[col1, col2,...], then use the array_positions function, setting the second parameter to be the value you're checking for. So, given your example above, this query:
SELECT id, array_positions(array[x1,x2,x3,x4,y1,y2,y3,y4], 1)
FROM tbl
ORDER BY id;
Will yield this result:
+----+-------------------+
| id | array_positions |
+----+-------------------+
| a | {1,4,5} |
| b | {1,2,4,7} |
| c | {1,2,3,4,6,7,8} |
+----+-------------------+
Here's a SQL Fiddle.

SQL: Find highest number if its in nvarchar format containing special characters

I need to pull the record containing the highest value, specifically I only need the value from that field. The problem is that the column is nvarchar format that contains a mix of numbers and special characters. The following is just an example:
PK | Column 2 (nvarchar)
-------------------
1 | .1.1.
2 | .10.1.1
3 | .5.1.7
4 | .4.1.
9 | .10.1.2
15 | .5.1.4
Basically, because of natural sort, the items in column 2 are sorted as strings. So instead of returning the PK for the row containing ".10.1.2" as the highest value i get the PK for the row that contains ".5.1.7" instead.
I attempted to write some functions to do this but it seems what I've written looked way more complicated than it should be. Anyone got something simple or complicated functions are the only way?
I want to make clear that I'm trying to grab the PK of the record that contains the highest Column 2 value.
This query might return what you desire
SELECT MAX(CAST(REPLACE(Column2, '.', '') as INT)) FROM table