SQL join with concat and substring - sql

So I'm attempting to do a join that requires both CONCAT and SUBSTRING.
Table one has a column with a date and location e.g. '02:00 IND'
Table two has a column with date/time e.g. '2020-10-10 02:00:00.000000' and another column with location e.g. 'IND'.
This is the statement that I'm trying but it isn't working:
SELECT *
FROM FIRST_TABLE
INNER JOIN SECOND_TABLE on FIRST_TABLE.TIME_LOCATION =
CONCAT(SUBSTRING(SECOND_TABLE.TIME,12,5) , SECOND_TABLE.LOCATION);
I am receiving the below error:
[SQL0171] Argument 1 of function
SUBSTRING not valid. Cause . . . . . : The data type, length, or value
of argument 1 of function SUBSTRING specified is not valid. Recovery .
. . : Refer to the DB2 for IBM i SQL Reference topic collection in the
Database category in the IBM i Information Center for more information
on scalar functions. Correct the arguments specified for the function.
Try the request again

There will be no space when you concat the substrings.
It will look like this:
02:00IND
I am guessing it is just returning a blank result as you have not mention it was returning an error :)

I got it to work if anyone ever has a similar issue. I am a beginner in SQL so I don't know if this will be helpful or not, I'm sure there is a better way of doing it.
Anyway, my issue was that the data types were incompatible. I cast the timestamp as time which left me with a 'HH.MM.SS' format. After that I had to cast it into a NVARCHAR to make a substring that excluded the seconds. And THEN I had to replace the '.' with a ':' to make the values match. It was a lot of work but I figured it out!
SELECT *
FROM FIRST_TABLE
INNER JOIN SECOND_TABLE on FIRST_TABLE.TIME_LOCATION =
CONCAT(CONCAT(REPLACE(SUBSTRING(CAST(TIME(SECOND_TABLE.TIME)AS NVARCHAR(8)), 1, 5),
'.', ':'), ' '), DSP134.LSDTID);

Related

How to SELECT a postgresql tsrange column as json?

I want to get a tsrange column returned as json but do not understand how get it to work in my query:
reserved is of type TSRANGE.
c.id and a.reservationid are of type TEXT.
-- query one
SELECT DISTINCT c.*, to_json(a.reserved) FROM complete_reservations c
JOIN availability a ON (c.id = a.reservationid)
throws
ERROR: could not identify an equality operator for type json
LINE 1: SELECT DISTINCT c.*, to_json(a.reserved) FROM complete_reser...
^
SQL state: 42883
Character: 22
it works if i try it like
-- query two
SELECT to_json('[2011-01-01,2011-03-01)'::tsrange);
Result:
"[\"2011-01-01 00:00:00\",\"2011-03-01 00:00:00\")"
and I do not understand the difference between both scenarios.
How do I get query one to behave like query two?
as pointed out in this comment by Edouard, there seems to be no JSON representation of a tsrange. Therefore I framed my question wrong.
In my concrete case it was sufficent to turn the tsrange to an array of the upper() and lower() values of the TSRANGE and cast those values as strings. this way i can use the output as is and let my downstream tools handle them as json.
SELECT DISTINCT c.*, ARRAY[to_char(lower(a.reserved),'YYYY-MM-DD HH:MI:SS'),to_char(upper(a.reserved),'YYYY-MM-DD HH:MI:SS')] reserved FROM complete_reservations_with_itemidArray c
JOIN availability a ON (c.id = a.reservationid)
which returns a value like this in the reserved column: {"2023-02-04 04:57:00","2023-02-05 04:57:00"} which can be parsed as json if needed.
I post this for reference. I am not sure if it exactly answers my question as it was framed.

Getting an error when using CONCAT in BigQuery

I'm trying to run a query where I combine two columns and separate them with an x in between.
I'm also trying to get some other columns from the same table. However, I get the following error.
Error: No matching signature for function CONCAT for argument types: FLOAT64, FLOAT64. Supported signatures: CONCAT(STRING, [STRING, ...]); CONCAT(BYTES, [BYTES, ...]).
Here is my code:
SELECT
CONCAT(right,'x',left),
position,
numbercreated,
Madefrom
FROM
table
WHERE
Date = "2018-10-07%"
I have tried also putting a cast before but that did not work.
SELECT Concast(cast(right,'x',left)), position,...
SELECT Concast(cast(right,'x',left)as STRING), position,...
Why am I getting this error?
Are there any fixes?
Thanks for the help.
You need to cast each value before the concat():
SELECT CONCAT(CAST(right as string), 'x', CAST(left as string)),
position, numbercreated, Madefrom
FROM table
WHERE Date = '2018-10-07%';
If you want a particular format, then use the FORMAT() function.
I also doubt that your WHERE will match anything. If Date is a string, then you probably want LIKE:
WHERE Date LIKE '2018-10-07%';
More likely, you should use the DATE function or direct comparison:
WHERE DATE(Date) = '2018-10-07'
or:
WHERE Date >= '2018-10-07' AND
Date < '2018-10-08'
Another option to fix your issue with CONCAT is to use FROMAT function as in below example
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1.01 AS `right`, 2.0 AS `left`
)
SELECT FORMAT('%g%s%g', t.right, 'x', t.left)
FROM `project.dataset.table` t
result will be
Row f0_
1 1.01x2
Note: in above specific example - you could use even simpler statement
FORMAT('%gx%g', t.right, t.left)
You can see more for supporting formats
Few recommendations - try not to use keywords as a column names/aliases. If for some reason you do use - wrap such with backtick or prefix it with table name/alias
Yet another comment - looks like you switched your values positions - your right one is on left side and left one is on right - might be exactly what you need but wanted to mention
Try like below by using safe_cast:
SELECT
CONCAT(SAFE_CAST( right as string ),'x',SAFE_CAST(left as string)),
position,
numbercreated,
Madefrom
FROM
table
WHERE
Date = '2018-10-07'

Translate function not returning relevant string in amazon redshift

I am trying to use a simple Translate function to replace "-" in a 23 digit string. The example of one such string is "1049477-1623095-2412303" The expected outcome of my query should be 104947716230952412303
The list of all "1049477-1623095-2412303" is present in a single column "table1". The name of the column is "data"
My query is
Select TRANSLATE(t.data, '-', '')
from table1 as t
However, it is returning 104947716230952000000 as the output.
At first, I thought it is an overflow error since the resulting integer is 20 digit so I also tried to use following
SELECT CAST(TRANSLATE(t.data,'-','') AS VARCHAR)
from table1 as t
but this is not working as well.
Please suggest a way so that I could have my desirable output
This is too long for a comment.
This code:
select translate('1049477-1623095-2412303', '-', '')
is going to return:
'104947716230952412303'
The return value is a string, not a number.
There is no way that it can return '104947716230952000000'. I could only imagine that happening if somehow the value is being converted to a numeric or bigint type.
Try regexp_replace()
Taking your own example, execute:
select regexp_replace('[string / column_name]','-');
It can be achieve RPAD try below code.
SELECT RPAD(TRANSLATE(CAST(t.data as VARCHAR),'-','') ,20,'00000000000000000000')

stream analytics query get error column name doesn't exist, but it does?

When I run my query in management studio it works fine, but in a stream analytics job it throws an error: Query compilation error: Invalid column name: 'afkorting'. Column with such name does not exist..
I downloaded the input tables to check if something went wrong with uploading, but that file does have that column name (and I double checked for capital letters, miswriting etc), so how can I fix this?
This is my query:
; WITH Check AS
(
SELECT afkorting, *
FROM Reizen RE
LEFT JOIN Gegevens AP
ON RE.ID = AP.code
)
SELECT *
FROM Check CH
JOIN Model VM
ON CH.afkorting = VM.Station
WHERE VM.h_station = VM.v_station
AND DATEPART(hour, CH.MsgReportDate) = VM.start_uur
AND (DATEPART(minute, CH.MsgReportDate) BETWEEN VM.start_minuut AND VM.eind_minuut)
AND DATEPART(weekday, CH.MsgReportDate) = VM.weekdag
Hope someone can help me!
*PROBLEM SOLVED: you need to give in all columnnames, so not SELECT * but SELECT column1, column2 and use the given prefixes of the table, in my case: AP.column1, RE.column2 etc*
Just summarize all comments above for resolving the issue, I did some testing for Stream Query language elements WITH, SELECT & JOIN. Here is my result list for the issue.
Without JOIN, using column names with symbol * in the WITH scope is correct for executing on ASA.
With JOIN, it's necessary to list all column names you want without symbol * for executing. The reason seems to be to avoid ambiguity with column name conflict.
you need to give in all column names, so not
SELECT * but SELECT column1, column2
and use the given prefixes of the table,
for example
in my case:
AP.column1, RE.column2 etc

How to substring records with variable length

I have a table which has a column with doc locations, such as AA/BB/CC/EE
I am trying to get only one of these parts, lets say just the CC part (which has variable length). Until now I've tried as follows:
SELECT RIGHT(doclocation,CHARINDEX('/',REVERSE(doclocation),0)-1)
FROM Table
WHERE doclocation LIKE '%CC %'
But I'm not getting the expected result
Use PARSENAME function like this,
DECLARE #s VARCHAR(100) = 'AA/BB/CC/EE'
SELECT PARSENAME(replace(#s, '/', '.'), 2)
This is painful to do in SQL Server. One method is a series of string operations. I find this simplest using outer apply (unless I need subqueries for a different reason):
select *
from t outer apply
(select stuff(t.doclocation, 1, patindex('%/%/%', t.doclocation), '') as doclocation2) t2 outer apply
(select left(tt.doclocation2), charindex('/', tt.doclocation2) as cc
) t3;
The PARSENAME function is used to get the specified part of an object name, and should not used for this purpose, as it will only parse strings with max 4 objects (see SQL Server PARSENAME documentation at MSDN)
SQL Server 2016 has a new function STRING_SPLIT, but if you don't use SQL Server 2016 you have to fallback on the solutions described here: How do I split a string so I can access item x?
The question is not clear I guess. Can you please specify which value you need? If you need the values after CC, then you can do the CHARINDEX on "CC". Also the query does not seem correct as the string you provided is "AA/BB/CC/EE" which does not have a space between it, but in the query you are searching for space WHERE doclocation LIKE '%CC %'
SELECT SUBSTRING(doclocation,CHARINDEX('CC',doclocation)+2,LEN(doclocation))
FROM Table
WHERE doclocation LIKE '%CC %'