ORDER BY A CUSTOM ORDER - sql-order-by

$words=$db->selectMultiRecords("select * from words where english like '$alphabet%' order by ......");
I have a list of words that I want to order by this order :
('a','b','g','G','d','D','e','f','k','K','h','p','o','x','q','i','j','l','m','n','u','r','R','V')
Uppercase letters and lowercase are not the same (d is not D)
Can you please help me ?

Use ORDER BY with FIELD:
SELECT *
FROM words
WHERE english LIKE '$alphabet%'
ORDER BY FIELD(LEFT(english, 1),
'a','b','g','G','d','D','e','f','k','K','h','p','o','x','q','i','j','l','m','n','u','r','R','V');
You seem to be using some PHP variant, but I don't recognize it, so I just gave the raw query. Also, you should avoid using PHP variables inside your SQL strings; use prepared statements instead.

Related

How to search for multiple values in a string column in a Cognos Oracle Query

I need to search an oracle table column for multiple word strings in cognos oracle query.
For example:
If Focus parameter returns multiple values as below
TRAINING
OMNIA
COUNTER
PROGRAM
And I need to search project.proj_name column like '%TRAINING%' or '%OMNIA%' or '%COUNTER%' or '%PROGRAM%'
I am trying below but I know it does only single value match not multiple. I want to know how to achieve multiple value match here.
'-99' in (#promptmany('Focus', 'string','-99')#) OR REGEXP_LIKE(proj_name, #promptmany('Focus', 'string','-99')#))
Working from Cognos Paul's solution to use output from promptmany as a table:
Assuming your query is named Q1...
Add a query. (Q2)
Add a SQL object to that query.
Set the Data source property for the SQL object.
Change the SQL Syntax property to IBM Cognos.
Define the query as
SELECT
parameterValue
FROM (VALUES
(#join('),(',split(',',promptmany('Scenarios','string',sq('N/A'))))#)
) query(parameterValue)
(change the names for your own use case)
Add a query. (Q3)
Add a join to the new query.
Add Q1 and Q2 to the empty boxes for the join leading to Q3.
Set the join as
[Q1].[proj_name] like '%' || [Q2].[parameterValue] || '%'
Add the required data items to Q3.
Since two keywords (from your parameter -> Q2) could be found in a single value (in Q1), you'll likely end up with duplicate rows. Cognos will probably handle this with its default aggregations, but keep a lookout.
Be careful with this. The new query (Q2) will probably be joined on the Cognos server, not on the database server. Be sure you have sufficient filters leading into this structure so Cognos is not trying to process your entire database.
This worked for me with SQL Server. I don't have an Oracle database to test against, but using IBM Cognos as the SQL Syntax should handle that.
To use REGEXP_LIKE to solve this problem, you'll need to get the second argument correct. I can't see any reason to see the error message ORA-00996: the concatenate operator is ||, not |, but I'm not working with your code in your system.
You don't specify which version of Cognos, or even which Cognos product, you are using. I'll assume Cognos Analytics 11.1.7.
To determine what Cognos Analytics is doing with your macro, create a very simple query with one item from the database (preferably from a very small table) and another data item that contains the macro. So the data item expression is:
#sq(join('|',split(',',promptmany('Focus','string','-99'))))#
When you run this, you may not be prompted. You'll see the value is -99. So to test this we'll need to remove the default so that the prompt becomes required.
#sq(join('|',split(',',promptmany('Focus','string'))))#
Be sure to enter more than one value when you test.
In my environment, the parameter returns a value that is my values surrounded by quotes (') and delimited by semicolons (;). So my tests produced the following:
expression
value
#sq(promptmany('Focus','string'))#
'PROGRAM';'COUNTER';'TRAINING'
#sq(join('|',split(',',promptmany('Focus','string'))))#
'PROGRAM';'COUNTER';'TRAINING'
#sq(join('|',split(';',promptmany('Focus','string'))))#
'PROGRAM'|'COUNTER'|'TRAINING'
replace(#sq(join('|',split(';',promptmany('Focus','string'))))#, '''', '')
PROGRAM|COUNTER|TRAINING
Your mileage may vary.
At this point, you know which macro to use in the REGEXP_LIKE function.

Question concerning sorting numbers by string/dealing with tiebreakers?

I am currently re-educating myself on Google sheets and I was wondering if there was a way to sort a set of numbers by string to deal with tiebreakers (i.e. a win/loss/tie record)
Using the SORT function, I was able to sort things correctly based on wins, but I want to be able to adjust it even further. Currently I have something like this...
3-0-0
1-4-0
1-3-0
1-2-0
1-1-0
when I want to have something like this, where the values with the lowest loss record goes on top instead...
3-0-0
1-1-0
1-2-0
1-3-0
1-4-0
Is there another function or a workaround possible to achieve something like this?
=SORT(A1:A5,INDEX(SPLIT(A1:A5,"-"),,1),0,INDEX(SPLIT(A1:A5,"-"),,2),1)
SPLIT(A1:A5,"-") by -
INDEX(SPLIT(A1:A5,"-"),,1) get first column of the split array
INDEX(SPLIT(A1:A5,"-"),,2) get second column
=SORT(A1:A5,col1,0,col2,1) Sort A1:A5 in descending order based on column1 and ascending order based on column 2
While in "human language" something like 3-0-0 could be called "a set of numbers" in "spreadsheet language" it's a text value.
To be able to use the built-in sorting functions in Google Sheets, you should split the values into columns, and guess what, there is a built-in function for that:
Select the column
Click on Data > Split text to columns
Select custom separarator and set -
There are a more options, like using a formulas and scripts.
Sample formula
=ArrayFormula(QUERY(
{A1:A5,REGEXEXTRACT(A1:A5,"-(\d{1,})-")},
"select Col1 order by Col2",0)
)
The above formula use a regular expression to extract the numbers between -, then use QUERY to sorth the values in A1:A5 in ascending order by using these values.

How to select a substring from Oracle blob field

I need to get part of a blob field which has some json data. one part of the blob is like this CustomData:{HDFC;1;0;sent} . I need separate values after CustomData like I need to get HDFC, 1, 0, sent separately.
This is what I have tried in two separate queries which works:
This gives me index of CustomData within payment_data blob field for example it returns 11000
select dbms_lob.instr(payment_data, utl_raw.cast_to_raw('CustomData'))
from table_x;
I am specifying 3rd parameter as what first query returned + length of test CustomData: to get {HDFC;1;0;sent}
select UTL_RAW.CAST_TO_VARCHAR2(dbms_lob.substr(payment_data,1000,11011))
from table_x;
Problem is I need to take dynamic offset in 2nd query and not run 1st query as individual. Specifying dynamic offset is not working with dbms_lob.substr() function. Any suggestions how can I combine these two queries into one?
Once I get {HDFC;1;0;sent}, I also need to get these delimited values separately, so combining these three into one would even be better if someone can help with it. I can use regexp_substr to get delimited text once I get first two combined.
If you want extract text data from blob first u need convert it to clob using dbms_lob.converttoclob.
If you have Oracle 12c or higher you may use JSON SQL functions, for example, JSON_TABLE.
If your Oracle version between 10 and 11 you may use regex functions or instr + substr if your version less than 10.

extract and replace parameters in SQL query using M-language

This question is related with this question. However, in that question I made some wrong assumptions...
I have a string that contains a SQL query, with or without one or more parameters, where each parameter has a "&" (ampersand sign) as prefix.
Now I want to extract all parameters, load them into a table in excel where the user can enter the values for each parameter.
Then I need to use these values as a replacement for the variables in the SQL query so I can run the query...
The problem I am facing is that extracting (and therefore also replacing) the parameter names is not that straight forward, because the parameters are not always surrounded with spaces (as I assumed in my previous question)
See following examples
Select * from TableA where ID=&id;
Select * from TableA where (ID<&ID1 and ID>=&ID2);
Select * from TableA where ID = &id ;
So, two parts of my question:
How can I extract all parameters
How can I replace all parameters using another table where the replacements are defined (see also my previous question)
A full solution for this would require getting into details of how your data is structured and would potentially be covering a lot of topics. Since you already covered one way to do a mass find/replace (which there are a variety of ways to accomplish in Power Query), I'll just show you my ugly solution to extracting the parameters.
List.Transform
(
List.Select
(
Text.Split([YOUR TEXT HERE], " "), each Text.Contains(_,"&")
),
each List.Accumulate
(
{";",")"}, <--- LIST OF CHARACTERS TO CLEAN
"&" & Text.AfterDelimiter(_, "&"),
(String,Remove) => Text.Replace(String,Remove,"")
)
)
This is sort of convoluted, but here's the best I can explain what is going on.
The first key part is combining List.Select with Text.Split to extract all of the parameters from the string into a list. It's using a " " to separate the words in the list, and then filtering to words containing a "&", which in your second example means the list will contain "(ID<&ID1" and "ID>=&ID2);" at this point.
The second part is using Text.AfterDelimiter to extract the text that occurs after the "&" in our list of parameters, and List.Accumulate to "clean" any unwanted characters that would potentially be hanging on to the parameter. The list of characters you would want to clean has to be manually defined (I just put in ";" and ")" based on the sample data). We also manually re-append a "&" to the parameter, because Text.AfterDelimiter would have removed it.
The result of this is a List object of extracted parameters from any of the sample strings you provided. You can setup a query that takes a table of your SQL strings, applies this code in a custom column where [YOUR TEXT HERE] is the field containing your strings, then expand the lists that result and remove duplicates on them to get a unique list of all the parameters in your SQL strings.

JDBC + statement.setEscapeProcessing(false)

Just want to know the exact effects of statement.setEscapeProcessing(false) as anywhere in documentation i am not finding proper explaination here are my questions
1) statement.setEscapeProcessing(false) will not any effects if we dont have escape clause in query . is this correct ?
2) If first one is correct why query modification happens even if i dont use any escape clause in my query but table name contains some special caharcter like ? and also statement.setEscapeProcessing(true) which is default. i tested this out here ? gets replaced with ':1' witout the quotes
sample query - SELECT * FROM CLIENT.\"abc?table\" where rownum=1
when i set statement.setEscapeProcessing(false) and run the above query it works i.e no replacement happens
3) if statement.setEscapeProcessing(true) does escape for the whole query then whta is the exact difference between escape processing true and escaping the values using preparedStatement
You should take a look at JDBC 4.0 specifications document, section 13.4 to understand more about setEscapeProcessing() method.

Resources